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

时间:2017-11-13 15:26:43

标签: sql tsql rows collapse

我的查询处于奇怪的境地。我的目标是显示每个人的多笔交易的存款和取款总额并显示。我得到多行,我需要折叠成一行。这一切都需要在一个查询中进行

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

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

3 个答案:

答案 0 :(得分:1)

使用条件聚合。 。 。 $expandConsole.ReadKey(); 的参数:

case

答案 1 :(得分:0)

使用子查询的解决方案

select t.lastname, t.firsname,sum(t.Withdrawal) Withdrawal ,sum(t.Deposit) Deposit,t.description from(
select lastname, firsname,
       isnull(case when upper(category) = 'W' then abs(principal) end,0) as Withdrawal,
       isnull(case when upper(category) = 'D' then abs(principal) end,0) as Deposit,
description
from table1 join
     table2
     on table2.id = table1.id join
     table3
     on table3.c = table2.c
where description = 'string'
)t group by t.lastname, t.firstname, t.description, t.category

答案 2 :(得分:0)

试试这个:

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 table1.id = table2.id 
       JOIN table3 ON table2.c = table3.c 
WHERE 
       description = 'string'
GROUP BY
lastname,firstname,description
相关问题