How Do I collapse rows on null values in t-sql?

2020-04-30 08:53发布

I'm in a weird situation with my query. My objective is to display the total deposits and withdrawals from multiple transactions for each person and display them. I am getting multiple rows that I need to collapse into one. This all needs to happen in one query

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

my result is

 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

and I am looking for

 lastname    firstname    Withdrawal    Deposit    description
 john         smith       346.00        140.34     string
 jane         doe         504.00        68.03      string

adding principal into the group does not work. any help on solving this will be greatly appreciated!

3条回答
我欲成王,谁敢阻挡
2楼-- · 2020-04-30 09:15

Solution using Subquery

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
查看更多
The star\"
3楼-- · 2020-04-30 09:16

Use conditional aggregation . . . the case is the argument to the 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
查看更多
Ridiculous、
4楼-- · 2020-04-30 09:17

Try this:

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
查看更多
登录 后发表回答