sql - 如何折叠 t-sql 中空值的行?

标签 sql t-sql group-by row

我的查询遇到了奇怪的情况。我的目标是显示每个人多笔交易的存款和取款总额并显示它们。我收到多行,需要将其合并为一行。这一切都需要在一个查询中发生

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

将主体添加到组中不起作用。任何有关解决此问题的帮助将不胜感激!

最佳答案

使用条件聚合。 。 。 casesum() 的参数:

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/

相关文章:

MySQL 查询或过程从多行计算的值返回表

mysql - Error-1054 'column name' 中的未知列 'field-list'

sql - SSIS 隐藏工作表作为 Excel 目标

sql - T-SQL 计数二叉树中的子节点?

c# - 如何构造将输入下拉框的数据?

python - Pandas 或 SQL 中异常的表缩减

mysql - Zend DB 为 Where 和 Order 子句使用一个列

php - 如果不需要进行查询,冗余数据是否可以?

sql-server - MS SQL Server 使用 select 插入表,同时输出到第三个表

python - 列出 pandas 数据框中每组的唯一值计数