在mysql 下執行如下命令:select use_city,count(*) from data where os="Windows 2003 Std" group by use_city;得到的結果為:
+-----------+----------+
| use_city | count(*) |
+-----------+----------+
| Beijing | 2 |
| Chengdu | 2 |
| Chongqing | 1 |
| Dalian | 2 |
| Fuzhou | 2 |
| Guangzhou | 2 |
| Hangzhou | 2 |
| Nanjing | 2 |
| Shanghai | 21 |
| Shenyang | 5 |
| Wuhan | 1 |
+-----------+----------+
11 rows in set (0.01 sec)
共有11條記錄,問題是其中有一個城市“Tianjing”是沒有記錄符合的,怎麼讓他顯示成
+-----------+----------+
| use_city | count(*) |
+-----------+----------+
| Beijing | 2 |
| Chengdu | 2 |
| Chongqing | 1 |
| Dalian | 2 |
| Fuzhou | 2 |
| Guangzhou | 2 |
| Hangzhou | 2 |
| Nanjing | 2 |
| Shanghai | 21 |
| Tianjing | 0 |
| Shenyang | 5 |
| Wuhan | 1 |
+-----------+----------+
讓它count為0的記錄也顯示出來,做法如下:
SELECT
use_city,
COUNT(CASE WHEN os='Windows 2003 Std' THEN 1 ELSE NULL END)
FROM
data
GROUP BY
use_city