[詳細描述]:
有如下表 table1:
————
id type
1? 1
2? 2
3? 1
4? 1
————
我們希望統計每個type的id數量.一般情況下我們會寫出如下sql語句:
select type, count(id) from table1 group by type;
得出如下結果:
————
type count(id)
1? ? 3
2? ? 1
————
但本問題的實際需求為,type值有可能為(1,2,3),只是剛好這張表中沒有type為3的數據.
所以我需要得到如下的結果方為正確:
————
type count(id)
1? ? 3
2? ? 1
3? ? 0
————
關鍵在于如何統計數據中不存在的type為3的count(并為0).
我的解決方案為:
select ifnull(avg(type), 0), count(*) from table1 where type = 1
union all
select ifnull(avg(type), 0), count(*) from table1 where type = 2
union all
select ifnull(avg(type), 0), count(*) from table1 where type = 3