使用SQL查询,我试图找到在给定月份内页面浏览量大于5的用户数。
到目前为止我所拥有的正是上述情况,但我无法添加至少5页浏览量的条件。它目前显示的是在给定月份内至少有1次页面查看的用户数。
SELECT CONCAT(MONTH(analytics.date),'/',YEAR(analytics.date)) AS DATE,
COUNT(analytics.id) AS views,
COUNT(DISTINCT users.id) AS num_users
FROM users
LEFT JOIN analytics ON users.id = analytics.user_id
WHERE users.banned = 0
AND analytics.id IS NOT NULL
GROUP BY YEAR(analytics.date), MONTH(analytics.date)
我尝试在where子句中添加AND views > 5
但是因为我得到一个未知列而无效。
我认为HAVING
子句不会起作用,因为这是在GROUP BY
之后应用的,我需要查找页面浏览量超过5的个人用户。
我还能怎样做到这一点?
答案 0 :(得分:2)
如果这是您的要求,那么您需要聚合两次,一次是在用户级别,另一次是在分析级别。或者,在where
子句中使用子查询。以下是您可能需要的内容:
SELECT CONCAT(MONTH(a.date),'/',YEAR(a.date)) AS DATE,
COUNT(a.id) AS views,
COUNT(DISTINCT u.id) AS num_users
FROM users u LEFT JOIN
analytics a
ON u.id = a.user_id
WHERE u.banned = 0 AND a.id IS NOT NULL AND
5 <= (SELECT COUNT(*) FROM analytics a2 WHERE a2.user_id = u.userid)
GROUP BY YEAR(a.date), MONTH(a.date);
这使用限制的总计数。
编辑:要加快子查询,请确保您在analytis(user_id, date)
上有索引。
答案 1 :(得分:1)
您必须使用子查询,因为您要选择哪些用户加入GROUP BY
。在这里,如果用户在WHERE
表中至少有五个条目,我们在analytics
子句中执行子查询以询问每一行。
SELECT CONCAT(MONTH(analytics.date),'/',YEAR(analytics.date)) AS DATE,
COUNT(analytics.id) AS views,
COUNT(DISTINCT users.id) AS num_users
FROM users
LEFT JOIN analytics ON users.id = analytics.user_id
WHERE users.banned = 0
AND (SELECT COUNT(*) FROM analytics AS a WHERE a.user_id = users.id) > 5
AND analytics.id IS NOT NULL
GROUP BY YEAR(analytics.date), MONTH(analytics.date)
如果您希望在给定月份内用户的观看次数超过5次,则必须修改查询,并且需要使用内部联接:
SELECT CONCAT(MONTH(analytics.date),'/',YEAR(analytics.date)) AS DATE,
COUNT(analytics.id) AS views,
COUNT(DISTINCT users.id) AS num_users
FROM users
JOIN analytics ON users.id = analytics.user_id
WHERE users.banned = 0
AND (SELECT COUNT(*) FROM analytics AS a WHERE a.user_id = users.id AND EXTRACT(YEAR_MONTH FROM a.date) = EXTRACT(YEAR_MONTH FROM analytics.date)) > 5
AND analytics.id IS NOT NULL
GROUP BY YEAR(analytics.date), MONTH(analytics.date)