从两张桌子中得到总和

时间:2016-05-18 16:54:57

标签: sql-server sql-server-2008 join sum

我有两张桌子。

Voucher 
V_Id Cost
1     400
2     500

Expense 
E_Id  V_Id  Cost
1      1     100
2      1     100
3      1     100

我需要加入他们才能获得

V_Id  V_Cost  E_Cost
1      400     300
2      500      0

我尝试过INNER JOIN但我得到了两个相同的值。请帮忙。

1 个答案:

答案 0 :(得分:1)

我将Expense表的SUM(Cost)作为E_Cost,然后使用Voucher左加入以获得预期结果:

SELECT V.V_Id, V.Cost AS V_Cost, ISNULL(E.E_Cost, 0) AS E_Cost
FROM Voucher V
LEFT JOIN (  SELECT V_Id, SUM(Cost) AS E_Cost
             FROM Expense 
             GROUP BY V_Id ) AS E ON E.V_Id = V.V_Id

给定数据的工作示例:

DECLARE @Voucher TABLE (V_Id INT, Cost INT)
INSERT INTO @Voucher (V_Id, Cost)
VALUES (1, 400), (2, 500)

DECLARE @Expense TABLE (E_Id INT, V_Id INT, Cost INT)
INSERT INTO @Expense (E_Id, V_Id, Cost)
VALUES (1, 1, 100), (2, 1, 100), (3, 1, 100)

SELECT V.V_Id, V.Cost AS V_Cost, ISNULL(E.E_Cost, 0) AS E_Cost
FROM @Voucher V
LEFT JOIN (  SELECT V_Id, SUM(Cost) AS E_Cost
             FROM @Expense 
             GROUP BY V_Id ) AS E ON E.V_Id = V.V_Id