我有4个表(A,B,C,D),其中包含列日期和金额(无ID)
我需要像波纹管一样的结果表。每个表总和(金额)按日期分组。我尝试了很多选择和加入查询,但没有得到确切的结果。 帮助我
表A
date amount
____________________________
03/07/2015 100
03/07/2015 200
04/07/2015 300
表B
date amont
____________________________
04/07/2015 300
表C
date
____________________________
05/07/2015 400
表D
date
____________________________
06/07/2015 500
06/07/2015 300
结果表
date Sum(A) Sum(B) Sum(C) Sum(D) Total
_______________________________________________________________
03/07/2015 300 - - - 300
04/07/2015 300 300 - - 600
05/07/2015 - - 400 - 400
06/07/2015 - - - 800 800
_______________________________________________________________
ToTal: 600 300 400 800 2100
答案 0 :(得分:4)
您可以先UNION ALL
每个表的行,然后添加其他列tbl
以确定记录的来源。
WITH CteUnion([date], amount, tbl) AS(
SELECT [date], amount, 'A' FROM A UNION ALL
SELECT [date], amount, 'B' FROM B UNION ALL
SELECT [date], amount, 'C' FROM C UNION ALL
SELECT [date], amount, 'D' FROM D
)
SELECT
[date],
A = SUM(CASE WHEN tbl = 'A' THEN amount END),
B = SUM(CASE WHEN tbl = 'B' THEN amount END),
C = SUM(CASE WHEN tbl = 'C' THEN amount END),
D = SUM(CASE WHEN tbl = 'D' THEN amount END),
Total = SUM(amount)
FROM CteUnion
GROUP BY [date]
使用子查询,而不是CTE
:
SELECT
[date],
A = SUM(CASE WHEN tbl = 'A' THEN amount END),
B = SUM(CASE WHEN tbl = 'B' THEN amount END),
C = SUM(CASE WHEN tbl = 'C' THEN amount END),
D = SUM(CASE WHEN tbl = 'D' THEN amount END),
Total = SUM(amount)
FROM (
SELECT [date], amount, 'A' AS tbl FROM A UNION ALL
SELECT [date], amount, 'B' FROM B UNION ALL
SELECT [date], amount, 'C' FROM C UNION ALL
SELECT [date], amount, 'D' FROM D
)t
GROUP BY [date]