2012-11-02 34 views
2

我需要生成相對於通過其居住國的分組計數後對我們的一些用戶的年齡的報告。查找用戶的平均年齡爲0的帖子,帖子1-5和> 5個帖子

這裏是我的架構的簡化版本現在:

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 

了空將代表誰擁有國沒有特定數量級別的用戶。例如,丹麥的每個人都有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挫敗...當... ))相當多(幾個小時)。上面的查詢是我知道我需要的基本事情。

謝謝!

回答

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)表達的作品沒有別的,當沒有在當條款是真正的指定的選項,將輸出一個空。所有的聚合運算符(包括Sum())都將忽略空值。

+2

流氓'END)'在第4行。也將有助於解釋如何/爲什麼這個工程。 *(例如AVG({1,2,3,NULL})在計算中不包含NULL。)* – MatBailie