select whbmbh ,zt,1 as tjsl from fyxx group by zt,whbmbh
select whbmbh,sum(case zt when '有效' then 1 end) as yxsl,sum(case zt when '暫緩' then 1 end )as zhsl,sum(case zt when '未知' then 1 end) as wzsl,sum(case zt when '我租' then 1 end) as wzsl,sum(case zt when '他租' then 1 end) as tzsl,sum(case zt when '我售' then 1 end) as wssl,sum(case zt when '他售' then 1 end) as tssl ,sum(case zt when '撤單' then 1 end) as cdsl,sum(case zt when '電話錯誤' then 1 end) as dhcwsl,sum(case zt when '待確認' then 1 end) as dqrsl,sum(case zt when '已駁回' then 1 end) as ybhsl from fyxx group by whbmbh
下面是摘自別人的博客
最近遇到一個問題,需要對一張表做統計,這個統計有什么特別之處值得我記錄了下來呢?大家知道SQL中聚合函數GROUP BY的結果一般為一列,即多個值通過聚合函數運算統計到一起,但是如何將不同條件的值統計到不同列中呢,即按條件統計到多個列中。舉個栗子:
YEAR | TYPE | VALUE |
2015 | 1 | 100 |
2015 | 2 | 200 |
2016 | 1 | 150 |
2016 | 2 | 300 |
2016 | 3 | 100 |
轉為:
YEAR | TYPE1 | TYPE2 | TYPE3 |
2015 | 100 | 200 | 0 |
2016 | 150 | 300 | 100 |
這時候我們除了用到GROUP BY之外還需要CASE WHEN,SQL如下:
SELECT year, SUM(CASE WHEN type=1 THEN value ELSE 0 END) as type1, SUM(CASE WHEN type=2 THEN value ELSE 0 END) as type2, SUM(CASE WHEN type=3 THEN value ELSE 0 END) as type3, FROM table_test GROUP BY year