2

我需要生成一份关于我们一些用户的年龄的报告,这些用户的帖子数按他们的居住国分组。

这是我现在架构的简化版本:

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 ...))挫败了很多(几个小时)。上面的查询只是我知道我需要的基本内容。

谢谢!

4

1 回答 1

1

尝试

 Select c.name,
    Avg(Case When pc.postCount == 0 Then pc.Age End) avgAgeNoPosts,
    Avg(Case When pc.postCount Between 1 And 5 Then pc.Age End) avgAge1_5Posts,
    Avg(Case When pc.postCount > 5 Age End) Then pc.Age End) avgAgeGT5Posts
 From users u
    Join countries c On c.id=u.country_id
    Join (Select user_id uid, Count(*) postCount
          From posts
          Group By user_id ) pc
       On pc.UId = u.id
 Group By c.name

为了解释为什么Sum(Case When ... End)表达式在没有 else 的情况下工作,当在 When 子句中指定的选项都不为真时,将输出空值。并且所有聚合运算符(包括 Sum() )将忽略空值。

于 2012-11-02T16:28:26.900 回答