查询并列出来自共享相同ID的许多表的多列

时间:2018-01-10 14:27:32

标签: sql sql-server sql-server-2016

我有两张桌子:

  • OctSales拥有帐户,消费,帐单列。
  • NovSales拥有帐户,消费,帐单列。

我希望看到所有帐户的销售额:出现在任何表格中

Example

1 个答案:

答案 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     |
+----+------------+------------+