sql查询相同列的差异

时间:2018-04-05 11:40:52

标签: sql sql-server sql-server-2008-r2

这是我的数据库显示我的销售借记。此处列类型取0作为到期金额,1作为付款金额。我正在尝试计算余额。

code Name   due bill date        type
--------------------------------------
113  ABC    30  9   2018-04-03    0
113  ABC    7   10  2018-04-03    0
113  ABC    20  11  2018-04-05    1
114  XYZ    25  25  2018-05-06    0

当从37

中减去20时,这是我想要的表格
code Name      due 
------------------
113 ABC        17
114 XYZ        25

我已经使用了这个查询

select code, name,SUM(amount) from Debit group by code, name, type

上述问题的正确查询是什么? 提前谢谢

3 个答案:

答案 0 :(得分:5)

你想要这样的东西:

select code, name,
       sum(case when type = 0 then due else - due end) as due
from t
where type in (0, 1)
group by code, name;

答案 1 :(得分:3)

这可以通过从[Type]子句中删除GROUP BY来解决,并添加CASE表达式:

SELECT code,
       [name],
       SUM(CASE [Type] WHEN 0 THEN 1 ELSE -1 END * amount) AS due
FROM Debit
GROUP BY code,
         [name];

答案 2 :(得分:1)

您还可以尝试以下查询

SELECT A.code, A.name, (CASE WHEN A.due>A.payment THEN a.due-A.payment
                        CASE WHEN A.due>0 THEN A.due ELSE 0 END) AS due FROM 
(SELECT code,name, sum(case when type = 1 then due end) due, 
                   sum(case when type = 0 then due end) payment 
FROM [table] GROUP BY code,name) A