我在编写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个信用报告的用户数量或更多)
这里的任何人都可以帮助我,或者让我知道如何实现这个目标吗?
答案 0 :(得分:1)
您的GROUP BY
子句实际上既是age
又是gender
,因为您正在尝试聚合这两个子句。考虑它的方法是你想要每age
和gender
只有一行,即男性/ 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个报告的总数等等。