我目前的结果是这个
| MonthYear | Table1 Amount | Table2 Amount |
|-----------|---------------|---------------|
| Jun-17 | 100 | 125 |
| Sep-17 | 50 | 50 |
我每月都会比较两张表中的总数。当两个表之间的总数不同时,我想将差异添加到另一个列
| MonthYear | Table1 Amount | Table2 Amount | Unknown |
|-----------|---------------|---------------|---------|
| Jun-17 | 100 | 125 | 25 |
| Sep-17 | 50 | 50 | 0 |
我已经实现了但是我如何将case语句添加为行而不是列,例如像这样的输出
| MonthYear | Table1 Amount | Table2 Amount |
|-----------|---------------|---------------|
| Jun-17 | 100 | 125 |
| Sep-17 | 50 | 50 |
| Unknown | | 25 |
可以这样做吗?任何帮助,将不胜感激。感谢
SQL小提琴 - http://sqlfiddle.com/#!6/8843b/1
答案 0 :(得分:1)
您可以使用ROLLUP
?
SELECT
t2.MonthYear,
CASE WHEN GROUPING(t2.MonthYear) = 0
THEN sum(t1.Amount)
END AS [Table1 Amount] ,
CASE WHEN GROUPING(t2.MonthYear) = 0
THEN sum(t2.Amount)
ELSE SUM(t2.amount) - SUM(t1.amount)
END AS [Table2 Amount]
FROM Table1 T1
JOIN
Table2 T2
ON T1.Code1 = T2.Code1
AND T1.InvoiceNumber = T2.InvoiceNumber
GROUP BY T2.MonthYear WITH ROLLUP
http://sqlfiddle.com/#!6/8843b/4
但是将价值置于table2金额下似乎是一种误导?