按MySQL中要求的年龄,性别和报告对数据进行分组

时间:2014-06-17 07:17:11

标签: mysql sql group-by having

我在编写MySQL语句/查询字符串时遇到问题。我有一张桌子(见下面的样本)

MySQL sample Table

它是一个包含性别,年龄和report_requested字段的示例表。我想要的输出是这样的:

20 years old, male | Total number of users | Total who requested min 1 report | total who requested 2 reports | total 3 or more reports

20 years old female | Total number of users | Total who requested min 1 report | total who requested 2 reports | total 3 or more reports

20 years old combined | Total number of users | Total who requested min 1 report | total who requested 2 reports | total 3 or more reports

21 years old, male | Total number of users | Total who requested min 1 report | total who requested 2 reports | total 3 or more reports

21 years old female | Total number of users | Total who requested min 1 report | total who requested 2 reports | total 3 or more reports

21 years old combined | Total number of users | Total who requested min 1 report | total who requested 2 reports | total 3 or more reports

......等等。

但是我很难接受它。我所知道的是确定在给定性别和年龄的情况下请求(1,2,3,...等)信用报告的用户数量。

这是我使用的:

SELECT COUNT(*) as cnt, report_requested 
FROM sampletable WHERE age = '39' 
AND gender = 'M' GROUP BY report_requested

结果如下:

enter image description here

它只返回20岁男性的数据,用户数量要求1个信用报告,2个信用报告最多8个(但这也是错误的,因为它应该结合请求3个信用报告的用户数量或更多)

这里的任何人都可以帮助我,或者让我知道如何实现这个目标吗?

1 个答案:

答案 0 :(得分:1)

您的GROUP BY子句实际上既是age又是gender,因为您正在尝试聚合这两个子句。考虑它的方法是你想要每agegender只有一行,即男性/ 20年1行,女性1行/ 20年,男性1行/ 21年等等你会这样做:

GROUP BY age, gender

而不是report_requested列,我认为您需要SUM(report_requested),并且条件是所请求的报告数量。这是通过CASE子句在SQL中处理的。所以你的查询看起来像这样:

SELECT AGE, GENDER, 
    SUM(CASE WHEN report_requested = 1 THEN 1 ELSE 0 END) AS 'Total who requested 1 report',
    SUM(CASE WHEN report_requested = 2 THEN 1 ELSE 0 END) AS 'Total who requested 2 reports',
    SUM(CASE WHEN report_requested >= 3 THEN 1 ELSE 0 END) AS 'Total who requested 3 or more reports'
FROM sampletable 
GROUP BY AGE, GENDER

让我知道它是怎么回事。我删除了WHERE子句,因为我认为它仅用于测试。

编辑:在下面的评论之后更新,不是请求1个报告的总请求总数,请求2个报告的总数等等。