小编典典

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

sql

我试图使用下面的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;

阅读 259

收藏
2021-03-17

共1个答案

小编典典

这个怎么样?

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
2021-03-17