【问题标题】:Group data by age, gender and report requested in MySQL按年龄、性别和 MySQL 中请求的报告分组数据
【发布时间】:2014-06-17 07:17:11
【问题描述】:

我在制定 MySQL 语句/查询字符串时遇到问题。我有一张桌子(请参阅下面的示例)

这是一个包含性别、年龄和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

结果如下:

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

这里的任何人都可以帮助我或告诉我如何完成此任务吗?

【问题讨论】:

    标签: mysql sql group-by having


    【解决方案1】:

    您的GROUP BY 子句实际上是agegender,因为您正在尝试聚合这两个子句。考虑它的方式是,您希望每个 agegender 正好有一行,即男性/20 岁 1 行,女性/20 岁 1 行,男性/21 岁 1 行,等等。所以你会这样做:

    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 子句,因为我认为这只是为了测试。

    编辑:在下面的 cmets 之后更新,这不是请求的总数,而是请求 1 份报告的总数,请求 2 份报告的总数等。

    【讨论】:

    • 真的是 AGE(report_requested) 还是 SUM(report_requested) ?
    • 确实是SUM(report_requested),谢谢指出。我修好了。
    • 它以某种方式工作,但它只显示每个年龄/性别请求的信用报告总数(请求总数)。我仍然需要获取请求报告总数的细分(请求 1 份信用报告、2 份信用报告等的用户数量)
    • 我想我可能需要使用 HAVING...?不太确定。
    • 我从你的问题中误解了那部分,但我已经更新了我的回复,试试看。如果您需要按聚合函数过滤(例如 HAVING count(*) > 5 以便仅显示所选行的总计数超过 5 的行),则通常需要 HAVING 子句。我认为这不适用于您的情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多