gpt4 book ai didi

MySQL - 在 CASE 中组合多个 WHEN 条件

转载 作者:IT老高 更新时间:2023-10-28 23:53:46 31 4
gpt4 key购买 nike

我正在尝试使用以下 CASE 子句将 2 行结果合并为 1 行。 ‘<26’应该只出现一次,结果应该合并。

SELECT  
CASE org.size
WHEN 0 THEN '<26'
WHEN 1 THEN '<26'
WHEN 2 THEN '26-50'
WHEN 3 THEN '51-100'
WHEN 4 THEN '101-250'
WHEN 5 THEN '251-500'
WHEN 6 THEN '501-1000'
WHEN 7 THEN '1001-5000'
ELSE '5000+' END
AS 'Size',
COUNT(DISTINCT org.id) AS '# of Companies'
FROM org INNER JOIN usr ON usr.orgid = org.id
INNER JOIN usr_role ON usr.id = usr_role.usrid
WHERE org.deleted = 0 AND usr.brnd = 1 AND usr_role.role = 1
GROUP BY org.size;

最佳答案

这个怎么样?

SELECT  CASE 
WHEN org.size IN (0, 1) THEN '<26'
WHEN org.size = 2 THEN '26-50'
WHEN org.size = 3 THEN '51-100'
WHEN org.size = 4 THEN '101-250'
WHEN org.size = 5 THEN '251-500'
WHEN org.size = 6 THEN '501-1000'
WHEN org.size = 7 THEN '1001-5000'
ELSE '5000+' END AS Size, ....

问题是您正在对记录 org.size 进行分组导致 <26在两个不同的组中,因为它们最初是 01 .

这会起作用,

GROUP BY CASE 
WHEN org.size IN (0, 1) THEN '<26'
WHEN org.size = 2 THEN '26-50'
WHEN org.size = 3 THEN '51-100'
WHEN org.size = 4 THEN '101-250'
WHEN org.size = 5 THEN '251-500'
WHEN org.size = 6 THEN '501-1000'
WHEN org.size = 7 THEN '1001-5000'
ELSE '5000+' END

关于MySQL - 在 CASE 中组合多个 WHEN 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18991091/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com