I am trying to display data is columns/subcolumns based on certain filter criteria using case when statement but not getting required output.
data:
ID ID2 Country Type 1 001 US A 1 009 US A 2 002 AU B 3 003 CA A 3 005 CA A 4 007 US B 5 001 FR B 6 003 US B 7 002 US A 8 004 NZ A
based on my current case statement, here is how my output looks:
Type Country Count B Other 2 B US 1 B Subtotal 3 A Other 4 A US 3 A Subtotal 7 Total 10
I want to display the following format, bonus if I can get the subtotal/totals:
Type-A Type-B US Other US Other 3 4 1 2
I also need Subtotals, and Grandtotals, but these need to be calculated separately.
SubTotal: 7 SubTotal: 3
Grand Total: 10
Advertisement
Answer
You can like this
select sum(case when Type = 'A' and Country = 'US' then 1 else 0 end) as US_TYPE_A, sum(case when Type = 'A' and Country != 'US' then 1 else 0 end) as Other_TYPE_A, sum(case when Type = 'B' and Country = 'US' then 1 else 0 end) as US_TYPE_B, sum(case when Type = 'B' and Country != 'US' then 1 else 0 end) as Other_TYPE_B from myTable