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

前端 未结 3 1312
误落风尘
误落风尘 2021-01-23 00:28

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

相关标签:
3条回答
  • 2021-01-23 00:50

    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
    
    0 讨论(0)
  • 2021-01-23 00:54

    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
    
    0 讨论(0)
  • 2021-01-23 01:00

    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
    
    0 讨论(0)
提交回复
热议问题