2017-06-04 52 views
0

我一定要顯示有多少用戶投票調查,但在年齡範圍分離。如何顯示所有Case然後當記錄即使NULL在MySQL

我目前的查詢工作正常;但是當特定範圍沒有任何用戶時,我遇到了麻煩。例如,如果的40-49歲之間沒有用戶贊成投票,那麼結果應該是:

  • age_1 [13-19] = 0
  • age_2 [20-29 ] = 3
  • age_3 [30-39] = 1個
  • age_4 [40-49] = 0
  • age_5 [50+] = 0

...而是我得到這個:

  • age_2 [20-29] = 3
  • age_3 [30-39] = 1

那麼,是什麼我需要的是所有年齡段都會出現在結果中,即使沒有匹配。這是我當前的查詢:

SELECT 
CASE 
    WHEN age BETWEEN 13 AND 19 THEN "age_1" 
    WHEN age BETWEEN 20 and 29 THEN "age_2" 
    WHEN age BETWEEN 30 and 39 THEN "age_3" 
    WHEN age BETWEEN 40 and 49 THEN "age_4" 
    WHEN age >= 50 THEN "age_5" 
END as age_range, 
COUNT(*) AS q 
FROM (SELECT user.id_user AS id_user, TIMESTAMPDIFF(YEAR, user.birthday, CURDATE()) AS age FROM user) AS udata 
JOIN poll_vote ON poll_vote.id_user = udata.id_user 
WHERE poll_vote.id_poll = 2 AND udata.age IS NOT NULL 
GROUP BY age_range 
ORDER BY age_range 

這裏的SQL Fiddle與示例數據。謝謝!

回答

1

我會使用一個左連接你的總數和聚結。

select totals.age_range, coalesce(ages.q,0) total from 
( 
    select 'age_1' age_range 
    union select 'age_2' age_range 
    union select 'age_3' age_range 
    union select 'age_4' age_range 
    union select 'age_5' age_range) totals 
left join (
    SELECT 
CASE 
    WHEN age BETWEEN 13 AND 19 THEN "age_1" 
    WHEN age BETWEEN 20 and 29 THEN "age_2" 
    WHEN age BETWEEN 30 and 39 THEN "age_3" 
    WHEN age BETWEEN 40 and 49 THEN "age_4" 
    WHEN age >= 50 THEN "age_5" 
END as age_range, 
COUNT(*) AS q 
FROM (SELECT user.id_user AS id_user, TIMESTAMPDIFF(YEAR, user.birthday, CURDATE()) AS age FROM user) AS udata 
JOIN poll_vote ON poll_vote.id_user = udata.id_user 
WHERE poll_vote.id_poll = 2 AND udata.age IS NOT NULL 
GROUP BY age_range 
ORDER BY age_range 
) ages 
on totals.age_range = ages.age_range 

- 結果

AGE_RANGE總

age_1 0

age_2 3

age_3 1

age_4 0

age_5 0

+1

鍛煉出色。謝謝! – andufo

+1

感謝您的SQL小提琴。它可以很容易地處理你的問題! –

相關問題