sql - 如果至少存在一个值,则获取计数列 - SQL
问题描述
如果 group by 子句中至少存在一个值,如何为每种颜色创建单独的列?每个颜色列是否需要一个带有 group by 子句的单独 select 语句。提前致谢。
例如
SELECT
COUNT(ColorID) AS IcdCodecount,
Colorname
-- Blue -> if at least one value exists in 1, 10, 12
-- Red -> if at least one value in 0, 3, 4, 15
-- White -> if at least one value in 11, 12, 13, 14
-- Yellow -> if at least one value in 20, 21, 22, 23
FROM
TestTable
WHERE ColorID IN (
1, 10, 12, -- blue
0, 3, 4, 15, -- Red
11, 12, 13, 14, -- White
20, 21, 22, 23, -- yellow)
GROUP BY Colorname
解决方案
您可以使用条件聚合:
(case when sum(case when colorId in (1, 10, 12) then 1 else 0 end) > 0 then 1 else 0 end) as is_blue,
(case when sum(case when colorId in (0, 3, 4, 15) then 1 else 0 end) > 0 then 1 else 0 end) as is_red,
(case when sum(case when colorId in (11, 12, 13, 14) then 1 else 0 end) > 0 then 1 else 0 end) as is_white,
(case when sum(case when colorId in (20, 21, 22, 23) then 1 else 0 end) > 0 then 1 else 0 end) as is_yellow
推荐阅读
- cxf - 如何使用 JDK 12 运行 Apache CXF wadl2java?
- mysql - 从 POLYGON 对象获取最小/最大点
- docker - 在预构建的节点映像中安装 RPM 包
- python-3.x - 有没有办法从列表编号制作标签?
- powershell - 尝试从根存储导出证书时,对象或属性已存在错误
- python - 如何设置守护进程在它死时杀死其进程组中的其他进程
- javascript - 在 Safari 中,3D Carousel 的中心不对,Edge,Chrome 工作正常
- spring-boot - 在聚合器的 forceRelease 后服务中发生异常时如何死信 RabbitMQ 消息
- javascript - Twitch tmi.js /host no_permissions
- java - 为什么我的 JButton 在放入 JPanel 的构造函数时没有显示?