[英]Summing columns in two tables then joining tables
I have two tables set up in the same way, but with different values. 我以相同的方式设置了两个表,但它们的值不同。 Here are samples from each:
以下是每个样本:
Table1: 表格1:
Date Code Count
1/1/2015 AA 4
1/3/2015 AA 2
1/1/2015 AB 3
Table2: 表2:
Date Code Count
1/1/2015 AA 1
1/2/2015 AA 0
1/4/2015 AB 2
I would like the result table to contain all unique date-code pairs, with any duplicates between the tables having the counts of the two summed. 我希望结果表包含所有唯一的日期代码对,并且表之间的任何重复项都要将两个计数加起来。
Output_Table: 输出表:
Date Code Count
1/1/2015 AA 5 /*Summed because found in Table1 and Table2*/
1/2/2015 AA 0
1/3/2015 AA 2
1/1/2015 AB 3
1/4/2015 AB 2
I have no primary key to connect the two tables, and the joins I have tried have either not kept all distinct date-code pairs or have created duplicates. 我没有主键来连接两个表,而我尝试过的联接要么没有保留所有不同的日期代码对,要么创建了重复项。
For reference, I am doing this inside a SAS proc sql statement. 作为参考,我正在SAS proc sql语句中执行此操作。
I'm on the road at the moment so I haven't run this, but: 我目前在路上,所以我还没有跑过,但是:
SELECT date ,
code ,
SUM([count])
FROM ( SELECT *
FROM table1
UNION ALL
SELECT *
FROM table2
) [tables]
GROUP BY date ,
code
ORDER BY date ,
code
Will do the trick. 会成功的。 I'll have a crack at the join version and edit this post when I get in front of a proper computer
我将在加入版本时遇到麻烦,并在使用适当的计算机前进行编辑
EDIT: 编辑:
Full outer joins and COALESCE will also do it, although is marginally slower, so It may depend on what else you have going on there! 完全外部联接和COALESCE也会执行此操作,尽管速度稍慢,所以这可能取决于您在那里进行的其他操作!
SELECT COALESCE(#table1.date, #table2.date) ,
COALESCE(#table1.code, #table2.code) ,
ISNULL(#table1.COUNT, 0) + ISNULL(#table2.COUNT, 0)
FROM #table1
FULL OUTER JOIN #table2 ON #table2.code = #table1.code
AND #table2.date = #table1.date
ORDER BY COALESCE(#table1.date, #table2.date) ,
COALESCE(#table1.code, #table2.code)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.