我有两张桌子:
OctSales
拥有帐户,消费,帐单列。 NovSales
拥有帐户,消费,帐单列。我希望看到所有帐户的销售额:出现在任何表格中
答案 0 :(得分:0)
请参阅此示例了解FULL JOIN
方法:
DECLARE @Oct AS TABLE (id INT, amount DECIMAL(15, 3))
DECLARE @Nov AS TABLE (id INT, amount DECIMAL(15, 3))
INSERT @Oct (id, amount)
VALUES ( 1, 35.4)
, ( 2, 40)
INSERT @Nov (id, amount)
VALUES ( 1, 35.4)
, ( 3, 80)
SELECT COALESCE(OCT.id, NOV.id) AS ID
, SUM(OCT.amount) AS OCT_Amount
, SUM(NOV.amount) AS NOV_Amount
FROM @Oct AS OCT
FULL JOIN @Nov AS NOV
ON NOV.id = OCT.id
GROUP BY COALESCE(OCT.id, NOV.id)
结果:
+----+------------+------------+
| ID | OCT_Amount | NOV_Amount |
+----+------------+------------+
| 1 | 35.400 | 35.400 |
| 2 | 40.000 | NULL |
| 3 | NULL | 80.000 |
+----+------------+------------+