Skip to content
Advertisement

Join three count queries and get results in to three columns

I want to combine three count queries and get results in to separate columns. This is how my data set looks like.

enter image description here

I have tried this

select id, sum(val = 3) as valcount3
from (select id, s1 as val from t1 union all
      select id, s2 from t1 union all
      select id, s3 from t1 union all
      select id, s4 from t1 union all
      select id, s5 from t1
     ) sub1
group by id
union all
select id, sum(val = 2) as valcount2
from (select id, s1 as val from t1 union all
      select id, s2 from t1 union all
      select id, s3 from t1 union all
      select id, s4 from t1 union all
      select id, s5 from t1
     ) sub
group by id
union all
select id, sum(val = 1) as valcount1
from (select id, s1 as val from t1 union all
      select id, s2 from t1 union all
      select id, s3 from t1 union all
      select id, s4 from t1 union all
      select id, s5 from t1
     ) sub
group by id;

This is my output

enter image description here

But expected output is something like this

enter image description here

Advertisement

Answer

Just use conditional aggregation . . . multiple times:

select id, sum(val = 3) as valcount3,
       sum(val = 2) as valcount2,
       sum(val = 1) as valcount1
from (select id, s1 as val from t1 union all
      select id, s2 from t1 union all
      select id, s3 from t1 union all
      select id, s4 from t1 union all
      select id, s5 from t1
     ) sub1
group by id;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement