sql查询同一列的差异
sql query for difference of same column
这是我的数据库,显示我的销售额借方。这里的列类型将 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
这是我想要的 table 37 减去 20
code Name due
------------------
113 ABC 17
114 XYZ 25
我用过这个查询
select code, name,SUM(amount) from Debit group by code, name, type
以上问题的正确查询是什么?
提前致谢
你想要这样的东西:
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;
这可以通过从 GROUP BY
子句中删除 [Type]
并添加 CASE
表达式来解决:
SELECT code,
[name],
SUM(CASE [Type] WHEN 0 THEN 1 ELSE -1 END * amount) AS due
FROM Debit
GROUP BY code,
[name];
您也可以尝试以下查询
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
这是我的数据库,显示我的销售额借方。这里的列类型将 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
这是我想要的 table 37 减去 20
code Name due
------------------
113 ABC 17
114 XYZ 25
我用过这个查询
select code, name,SUM(amount) from Debit group by code, name, type
以上问题的正确查询是什么? 提前致谢
你想要这样的东西:
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;
这可以通过从 GROUP BY
子句中删除 [Type]
并添加 CASE
表达式来解决:
SELECT code,
[name],
SUM(CASE [Type] WHEN 0 THEN 1 ELSE -1 END * amount) AS due
FROM Debit
GROUP BY code,
[name];
您也可以尝试以下查询
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