带有子查询的MySQL CASE语句,用于直方图

时间:2017-03-10 04:54:24

标签: mysql sql

我正在尝试收集数据以创建直方图。我想创建用户登录系统的次数的直方图。我的目标是利用this回答中的函数,但如果有更好的方法,那对我来说也没关系。

我的登录表与此类似:

datetime | userid

我的第一步是计算用户登录的次数:

select count(userid) from logins group by userid

这将返回一个类似于:

的漂亮结果集
1325
761
4012
1204
662
1841
15
1698
...

我的问题是,我如何调整它以利用链接答案中的SELECT CASE WHEN方法。该代码如下所示:

SELECT CASE WHEN age BETWEEN 13 AND 17 THEN '13-17' 
            WHEN age BETWEEN 18 AND 25 THEN '18-25' 
            ELSE '26+' END AS AgeGroup,
    COUNT(*) AS total
FROM MyTable
GROUP BY AgeGroup

在我的情况下,age子句中的WHEN是一个我认为不需要为每个WHEN运行的子查询。什么是利用我必须在这些箱中使用的计数的有效方法?

3 个答案:

答案 0 :(得分:1)

看起来您正在寻找登录次数范围,在这种情况下,您首先计算每个用户的登录尝试次数,然后将各个计数合并到不同的存储桶中。

以下查询将为您提供 1-2 次登录的用户数 3-4次 4 + 次。

SELECT CASE WHEN total_logins BETWEEN 1 AND 2 THEN '1-2' 
            WHEN total_logins BETWEEN 3 AND 4 THEN '3-4' 
            ELSE '4+' 
       END AS LoginGroup,
       COUNT(userid) AS total
FROM (
  SELECT userid, COUNT(*) AS total_logins 
  FROM login 
  GROUP BY userid
) t
GROUP BY LoginGroup

工作小提琴:http://sqlfiddle.com/#!9/a66396/2

如果您需要根据实际登录次数制作存储桶,请使用SUM(total_logins)代替COUNT(user_id),如下面的查询:

SELECT CASE WHEN total_logins BETWEEN 1 AND 2 THEN '1-2' 
            WHEN total_logins BETWEEN 3 AND 4 THEN '3-4' 
            ELSE '4+' 
       END AS LoginGroup,
       SUM(total_logins) AS total
FROM (
  SELECT userid, COUNT(*) AS total_logins 
  FROM login 
  GROUP BY userid
) t
GROUP BY LoginGroup

答案 1 :(得分:0)

您需要通过以下方式将案例添加到论坛:

select case when age between 13
                and 17 then '13-17' when age between 18
                and 25 then '18-25' else '26+' end as AgeGroup,
    COUNT(*) as total
from MyTable
group by case when age between 13
                and 17 then '13-17' when age between 18
                and 25 then '18-25' else '26+' end

如果你想写一次案例,请执行:

select AgeGroup,
    count(*) as total
from (
    select case when age between 13
                    and 17 then '13-17' when age between 18
                    and 25 then '18-25' else '26+' end as AgeGroup
    from MyTable
    ) t
group by AgeGroup

答案 2 :(得分:0)

请查看此代码。

SELECT 
CASE age 
    WHEN BETWEEN 13 AND 17 THEN '13-17' 
    WHEN BETWEEN 18 AND 25 THEN '18-25' 
    ELSE '26+'
END AS AgeGroup,
COUNT(*) AS total
FROM MyTable
GROUP BY CASE age 
    WHEN BETWEEN 13 AND 17 THEN '13-17' 
    WHEN BETWEEN 18 AND 25 THEN '18-25' 
    ELSE '26+'
END