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 |
Hrungdak
Starting Member
2 Posts |
Posted - 2013-09-17 : 09:35:02
|
Hello,I have two tables:Table1:--------------------------------Art ID Count1123 1 10123 2 34123 3 13234 1 1345 1 30345 2 20Table2:---------------------------------Art ID Count2123 1 8123 2 15345 1 50I need a result in this manner:Result-------------------------------------------------------------------Art Count1 Count2123 57 23234 1 0345 50 50I had many attempts with SUM and GROUP BY and JOINS, but I dont get it right. Can anyone help me here?Alex |
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2013-09-17 : 10:11:01
|
Here is one way.SELECT COALESCE(a.art,b.art) AS art, SUM(count1) AS count1, SUM(count2) AS count2FROM Table1 a FULL JOIN Table2 b ON a.art = b.artGROUP BY COALESCE(a.art,b.art); |
|
|
sigmas
Posting Yak Master
172 Posts |
Posted - 2013-09-17 : 10:11:12
|
select isnull(t1.art,t2.art) as art,isnull(count1, 0) as count1,isnull(count2, 0) as count2from(select art, sum(count1) as Count1from table1group by art)t1full join(select art, sum(count2) as Count2from table2group by art)t2on t1.art = t2.art |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2013-09-17 : 21:25:21
|
[code]SELECT Art, Count1 = SUM(Count1), Count2 = SUM(Count2)FROM( SELECT Art, Count1, Count2 = 0 FROM TABLE1 UNION ALL SELECT Art, Count1 = 0, Count2 FROM TABLE2) dGROUP BY Art[/code] KH[spoiler]Time is always against us[/spoiler] |
|
|
Hrungdak
Starting Member
2 Posts |
Posted - 2013-09-18 : 00:49:23
|
Result of James K:art count1 count2123 114 69234 1 345 50 100Count1 is multiplied by the number of records in table 2. Same problem as i had.Result of Sigmas:art count1 count2123 57 23234 1 0345 50 50Looks perfect to me.Result of khtan:art count1 count2123 57 23 234 1 0345 50 50Also perfect. Thanks a lot. You were a great help. |
|
|
|
|
|
|
|