mysql - 加入三个计数查询并将结果放入三列
问题描述
我想组合三个计数查询并将结果放入单独的列中。这就是我的数据集的样子。
我试过这个
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;
这是我的输出
但预期的输出是这样的
解决方案
只需使用条件聚合。. . 多次:
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;
推荐阅读
- azure-logic-apps - 隐藏表单识别器逻辑应用结果为逻辑应用中的 CSV
- java - 我想将 Fragment 类中的变量用于 Home 类
- android - Flutter:如何在没有“RenderOverflow”错误的情况下将两个小部件放在另一个下方?
- javascript - 重命名 Vue mapState 状态
- ios - Moodle + H5P + iframe+ iPhone
- c# - 将多个引用表连接到主表的 Lambda 语法
- math - 缩放后如何计算网格内给定点的坐标
- python - 在python中计算给定数字的前两个因子(除了1)的程序
- visual-studio-code - 使用 Intelephense 的 VS 代码不读取对象的可用方法
- python - 如何转换
python中元组中的数据?