我有两个表,名为Table-A和Table-B.请参考给定的表格.我想在两个表中获取’Value’列的聚合后加入这些.例如;
TABLE-A
Name Value1 ABC 10 ABC 18 ABC 12 DEF 5 XYZ 15 XYZ 16
TABLE-B
Name Value2 ABC 15 ABC 5 XYZ 9
我的预期结果是,
结果
Name Value1 Value2 ABC 40 20 DEF 5 0 XYZ 31 9
希望你理解我的问题.任何帮助将不胜感激.
解决方法
试试这个 –
SELECT a.Name,Value1 = ISNULL(Value1,0),Value2 = ISNULL(Value2,0) FROM ( SELECT Name,Value1 = SUM(Value1) FROM dbo.[TABLE-A] GROUP BY Name ) a LEFT JOIN ( SELECT Name,Value2 = SUM(Value2) FROM dbo.[TABLE-B] GROUP BY Name ) b ON a.Name = b.Name