比较来自2个不同表格的列,得出金额

时间:2015-09-04 00:13:12

标签: sql

我有一个场景,我有2个表具有相同的外键和数量列,如下所示:

TABLE 1:
ForeignKey       Amount
----------      -------------
12              20.0
12              30.0
13              20.0
21              10.0
21              10.0

TABLE 2:
ForeignKey       Amount
----------      -------------
12              60.0
12              25.0
13              30.0
21              10.0
21              10.0


EXPECTED OUTPUT:
ForeignKey       Amount
----------      -------------
12              35.0
13              10.0
21              0

我正在使用MSSQL

我想比较每张表的每张ForeignKey的金额,并获得差异。我意识到我可以将它们放入DataTable对象(C#)并进行一些复杂的循环,但我想知道我是否可以采用更优雅的SQL方法。我对SQL不是很强。有人能指出我可以探索的大方向,以解决这个问题吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

;with t as (select ForeignKey,amount from [table 1]
union
select ForeignKey,-amount from [table 2])
select ForeignKey,sum(amount) from t
group by ForeignKey

答案 1 :(得分:0)

SELECT T1.SUM1-T2.SUM1 AS DIFFERENCE FROM
(SELECT [FOREIGNKEY],SUM(AMOUNT) AS SUM1
FROM TABLE1
GROUP BY [FOREIGNKEY]) AS T1 INNER JOIN (SELECT [FOREIGNKEY],SUM(AMOUNT) AS SUM1
FROM TABLE2
GROUP BY [FOREIGNKEY]) AS T2 ON T1.FOREIGNKEY = T2.FOREIGNKEY

答案 2 :(得分:0)

SELECT t1.ForeignKey, t1.total AS total1, t2.total AS total2, t1.total-t2.total AS difference
FROM 
(
    SELECT ForeignKey,sum(Amount) AS total 
    FROM table1 
    GROUP BY ForeignKey
) t1 
INNER JOIN 
(
    SELECT ForeignKey,sum(Amount) AS total 
    FROM table2
    GROUP BY ForeignKey
) t2 
ON t1.ForeignKey=t2.ForeignKey