0

Does anyone have a solution how to group sums of two categories with case statements?

In the below screenshot i would like to merge two rows to one and just display PE and NPE sums in the columns flag1total and flag2total, but it's not working.

This is the SQL I have at the moment:

select type, flag, coalesce(sum(value),0) total,
case when flag = "NPE" then coalesce(sum(value),0) else "" end as flag1total,
case when flag = "PE" then coalesce(sum(value),0) else "" end as flag2total
from maintable
group by type, flag;

screenshot

The data looks like this

 type     flag          value
 P_OTH    PE            23525
 P_OTH    PE            13525
 P_CRE    PE            232525
 P_OTH    PE            4525
 ....

The expected result is this (one line per type and vectorized sums for the flags):

 type     flag          total      flag1total   flag2total
 P_OTH    PE, NPE       3023624    1132707      1890917
dfhdfh
  • 35
  • 1
  • 6

2 Answers2

1

You need to use case inside your sum function. Try something like this:

select type, coalesce(sum(value),0) total,
    coalesce(sum(case when flag = "NPE" then value else 0 end),0)   as flag1total,
    coalesce(sum(case when flag = "PE" then value else 0 end),0)  as flag2total
 from maintable
 group by type;

Note that 'flag' can't be in group by clause.

1

Do you need below -

SELECT  type
       ,GROUP_CONCAT(flag, ', ') flag
       ,coalesce(sum(value),0) total
       ,coalesce(sum(case when flag = "NPE" then value else 0 end),0)   as flag1total
       ,coalesce(sum(case when flag = "PE" then value else 0 end),0)  as flag2total
 from maintable
 group by type;
Ankit Bajpai
  • 13,128
  • 4
  • 25
  • 40