我需要生成一份关于我们一些用户的年龄的报告,这些用户的帖子数按他们的居住国分组。
这是我现在架构的简化版本:
DESCRIBE countries;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(45) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
DESCRIBE users;
+------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| age | int(11) | NO | | NULL | |
| country_id | int(11) | NO | MUL | NULL | |
+------------+---------+------+-----+---------+----------------+
DESCRIBE posts;
+---------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| content | text | NO | | NULL | |
| user_id | int(11) | NO | MUL | NULL | |
+---------+-------------+------+-----+---------+----------------+
我想要一个看起来像这样的结果集:
country.name | AVG(age of users with 0 posts) | AVG(age of users with 1-5 posts | AVG(age of users with 1-5 posts
----------------------------------------
Denmark | 17.4 | 23.2 | NULL
Germany | 20.1 | 27.8 | 34.7
England | 31.1 | NULL | 28.3
其中 NULL 表示在特定后计数级别没有用户的国家/地区。例如,丹麦的每个人都有 0 到 5 个帖子,仅此而已。我想它不必说NULL,但应该清楚的是,这个值是不确定的。
到目前为止,这是我的查询:
SELECT
c.name,
AVG(something) AS avg_age_with_no_posts,
AVG(something) AS `avg_age_with_1-5_posts`,
AVG(something) AS `avg_age_with_gt5_posts`
FROM
users u
JOIN posts p ON p.user_id=u.id
JOIN countries c ON c.id=u.country_id
GROUP BY c.id;
我知道这并不多,但实际上我已经用其他子句(嵌套选择、HAVING、COUNT(CASE ... WHEN ...))挫败了很多(几个小时)。上面的查询只是我知道我需要的基本内容。
谢谢!