Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
How do i join the following 2 tables.Orders Table:CustomerID | Name |Date 1 | order1 | 2010-01-01 2 | order2 | 2010-01-012 | order3 | 2010-04-01Calls Table:CustomerID | Name |Date 1 | call1 | 2010-01-01 3 | call2 | 2010-06-012 | call3 | 2010-05-01I want to join the two tables by date , Result:Date | Orders | Calls2010-01-01 | 2 | 12010-04-01 | 1 | 02010-05-01 | 0 | 12010-06-01 | 0 | 1how do i join them? thx!
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts
Posted - 2010-08-10 : 12:14:33
You need a full outer join.
select coalesce(a.Date,b.Date) as Date,coalesce(a.cnt,0) as Orders,coalesce(b.cnt,0) as Callsfrom(select Date, Count(*) as cnt from Orders group by Date) afull outer join (select Date, Count(*) as cnt from Calls group by Date) b on a.Date = b.Date
shaharru
Yak Posting Veteran
72 Posts
Posted - 2010-08-10 : 13:14:41
thx maybe it will be wise to change the table structure? if so any idea which structure will make it easier to get the results i wanted?
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2010-08-10 : 13:16:26
or
SELECT Date,COUNT(Order) AS Orders,COUNT(Call) AS CallsFROM( SELECT Date,Name AS Order,CAST(NULL AS varchar(100)) AS CallFROM OrdersUNION ALLSELECT Date,NULL,NameFROM Calls)tGROUP BY Date
------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/