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.
Author |
Topic |
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2007-02-21 : 07:46:07
|
jansci writes "hello,i'm a newbie to sql programming but one type of query that perplexed me was how to do the following:Table1Date Ship---- ----2/1 452/3 872/4 23Table2Date Rcvd---- ----2/1 342/2 482/3 332/5 55Final_TableDate Ship Rcvd---- ---- ----2/1 45 342/2 48 null2/3 87 332/4 23 null2/5 null 55I've tried all the types of joins and where clauses but cant come up with something like the Final_Table.Hope to hear from you soon!Thanks!" |
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2007-02-21 : 07:47:42
|
You didn't try the FULL JOIN, that will do the trick:SELECT COALESCE(T1.Date, T2.Date) AS Date, T1.Ship, T2.RcvdFROM Table1 T1 FULL JOIN Table2 T2 ON T1.Date=T2.Date |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-02-21 : 08:22:18
|
[code]-- prepare sample datadeclare @table1 table (date varchar(3), ship tinyint)insert @table1select '2/1', 45 union allselect '2/3', 87 union allselect '2/4', 23declare @table2 table (date varchar(3), rcvd tinyint)insert @table2select '2/1', 34 union allselect '2/2', 48 union allselect '2/3', 33 union allselect '2/5', 55-- FULL JOINSELECT COALESCE(T1.Date, T2.Date) AS Date, SUM(T1.Ship) AS Ship, SUM(T2.Rcvd) AS RcvdFROM @Table1 AS T1FULL JOIN @Table2 AS T2 ON T2.Date = T1.DateGROUP BY COALESCE(T1.Date, T2.Date)ORDER BY 1-- UNION ALLSELECT Date, SUM(Ship) AS Ship, SUM(Rcvd) AS RcvdFROM ( SELECT Date, Ship, 0 AS Rcvd FROM @Table1 UNION ALL SELECT Date, 0, Rcvd FROM @Table2 ) AS dGROUP BY DateORDER BY 1[/code]Peter LarssonHelsingborg, Sweden |
 |
|
|
|
|
|
|