我的查询遇到了奇怪的情况。我的目标是显示每个人多笔交易的存款和取款总额并显示它们。我收到多行,需要将其合并为一行。这一切都需要在一个查询中发生
SELECT
lastname,
firsname,
case when upper(category) = 'W' then sum(abs(principal)) end as Withdrawal,
case when upper(category) = 'D' then sum(abs(principal)) end as Deposit,
description
FROM
table1
JOIN table2 ON table1.id = table2.id
JOIN table3 ON table2.c = table3.c
WHERE
description = 'string'
GROUP BY
lastname,
firstname,
description,
category
我的结果是
lastname firstname Withdrawal Deposit description
john smith null 140.34 string
john smith 346.00 null string
jane doe null 68.03 string
jane doe 504.00 null string
我正在寻找
lastname firstname Withdrawal Deposit description
john smith 346.00 140.34 string
jane doe 504.00 68.03 string
将主体添加到组中不起作用。任何有关解决此问题的帮助将不胜感激!
最佳答案
使用条件聚合。 。 。 case
是 sum()
的参数:
select lastname, firsname,
sum(case when upper(category) = 'W' then abs(principal) end) as Withdrawal,
sum(case when upper(category) = 'D' then abs(principal) end) as Deposit,
description
from table1 join
table2
on table2.id = table1.id join
table3
on table3.c = table2.c
where description = 'string'
group by lastname, firstname, description
关于sql - 如何折叠 t-sql 中空值的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47267816/