在大小写时使用sum函数

时间:2017-06-06 15:50:44

标签: mysql

SELECT  '2017-05-30' AS `short_date`,
        'Stats' AS `group`,
        'Active ' AS `subgroup`,
         '' AS `row`,
         CASE
WHEN COUNT(DISTINCT(guild_name)) >= 1 AND  COUNT(DISTINCT(guild_name)) <= 5   THEN '1 - 5 ' 
WHEN COUNT(DISTINCT(guild_name)) >= 6 AND COUNT(DISTINCT(guild_name)) <= 10  THEN '6 - 10 '
WHEN COUNT(DISTINCT(guild_name)) >= 11 AND COUNT(DISTINCT(guild_name)) <= 15 THEN '11 - 15 '
WHEN COUNT(DISTINCT(guild_name)) >= 16 AND COUNT(DISTINCT(guild_name)) <= 20 THEN '16 - 20 '
WHEN COUNT(DISTINCT(guild_name)) >= 21 AND COUNT(DISTINCT(guild_name)) <= 25 THEN '21 - 25 '
WHEN COUNT(DISTINCT(guild_name)) >= 30 THEN '> 30' END AS `value`
FROM  table
WHERE guild_name !=0
GROUP BY
                `short_date`,
                `group`,
                `subgroup`

如何不计算每种情况下的值,如何计算一次并在每种情况下使用?

1 个答案:

答案 0 :(得分:3)

如何将计数移动到子查询并将案例移到外面,如下所示:

select `short_date`, `group`, `subgroup`, `row`,   
CASE
    WHEN nb_guild >= 1 AND nb_guild <= 5   THEN '1 - 5 ' 
    WHEN nb_guild >= 6 AND nb_guild <= 10  THEN '6 - 10 '
    WHEN nb_guild >= 11 AND nb_guild <= 15 THEN '11 - 15 '
    WHEN nb_guild >= 16 AND nb_guild <= 20 THEN '16 - 20 '
    WHEN nb_guild >= 21 AND nb_guild <= 25 THEN '21 - 25 '
    WHEN nb_guild >= 30 THEN '> 30' 
END AS `value`
from 
(
    SELECT  '2017-05-30' AS `short_date`,
            'Stats' AS `group`,
            'Active ' AS `subgroup`,
            '' AS `row`,
            COUNT(DISTINCT(guild_name)) as nb_guild
    FROM  table
    WHERE guild_name !=0
    GROUP BY
                    `short_date`,
                    `group`,
                    `subgroup`
) as subquery

这样,您的计数只会在子查询中执行一次,而您的外部查询会对结果结果集执行处理。