首页 > 解决方案 > 加入三个计数查询并将结果放入三列

问题描述

我想组合三个计数查询并将结果放入单独的列中。这就是我的数据集的样子。

在此处输入图像描述

我试过这个

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;

这是我的输出

在此处输入图像描述

但预期的输出是这样的

在此处输入图像描述

标签: mysqlsqljoincount

解决方案


只需使用条件聚合。. . 多次:

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;

推荐阅读