sql - SQL 按多个分类列分组并计数
问题描述
我有 3 个具有相同值范围的分类列:0/1 和 NULL。
SQL 中的列:
第 1 列 | 第 2 列 | 第 3 列 |
---|---|---|
0 | 1 | 1 |
0 | 1 | 0 |
1 | 无效的 | 1 |
无效的 | 0 | 1 |
我想要这样的每个类别的计数:
类别 | Cnt_Col1 | Cnt_Col2 | Cnt_Col3 |
---|---|---|---|
0 | 2 | 1 | 1 |
1 | 1 | 2 | 3 |
无效的 | 1 | 1 | 0 |
有人知道这在 SQL 中是如何实现的吗?以下查询未给出预期结果:
按 column1、column2、column3 从表组中选择 count(*)、column1、column2、column3
解决方案
我认为你想取消透视然后聚合。在通用 SQL 中,您可以使用:
select category,
sum(case when which = 'column1' then 1 else 0 end) as cnt_col1,
sum(case when which = 'column2' then 1 else 0 end) as cnt_col2,
sum(case when which = 'column3' then 1 else 0 end) as cnt_col3
from ((select column1 as category, 'column1' as which from t) union all
(select column2 as category, 'column2' as which from t) union all
(select column3 as category, 'column3' as which from t)
) c
group by category;
在 SQL Server 中,我建议APPLY
取消透视:
select v.category,
sum(case when v.which = 'column1' then 1 else 0 end) as cnt_col1,
sum(case when v.which = 'column2' then 1 else 0 end) as cnt_col2,
sum(case when v.which = 'column3' then 1 else 0 end) as cnt_col3
from t cross apply
(values (column1, 'column1'),
(column2, 'column2'),
(column3, 'column3')
) v(category, which)
group by v.category;
推荐阅读
- postgresql - 函数 to_number(bigint) 不存在
- javascript - 过滤不适用于通过函数构造的字段
- reactjs - Cuba-Platform ReactUI - 文件上传
- java - Spring Boot 方面的延迟导致连接点方法的延迟
- reactjs - 如何在 React Recharts 中将两个 Y 轴围绕 0 对齐?
- pandas - 创建变量的函数
- c# - 负载测试发生 Redis 超时(无可用连接)
- watson-assistant - 为什么 Twilio Flex HOLD MUSIC TWIML 在 25 到 30 秒后播放 如果从 watson 助手进行呼叫转移
- jquery - 仅显示与选择选项 laravel 中的类别相关的子类别
- angular - 如何在Angular中单击外部时关闭元素?