2017-05-17 68 views
1

我要問關於MySQL的多個罪名一些問題,所以IHAVE這樣的數據:MYSQL COUNT從DATE數據

| name | date      | act | 
------------------------------------------------ 
| abc | 2014-02-03 07:05:18   | 1 | 
| abc | 2014-02-03 08:05:18   | 1 | 
| abc | 2015-02-03 07:05:18   | 1 | 
| ghi | 2014-02-03 07:05:18   | 1 | 
| ghi | 2015-02-03 07:05:18   | 1 | 
| klm | 2014-02-03 07:05:18   | 1 | 
| klm | 2014-04-01 07:05:18   | 1 | 

然後我要讓這樣的報告:

| name | count(2014) | count(2015) | 
------------------------------------------------ 
| abc |  2  |  1  | 
| ghi |  1  |  1  | 
| klm |  2  |  0  | 

如何進行計數查詢?

+0

日期格式爲TIMESTAMP –

+0

多少年的數據是在表中,如果你將與靜態的解決方案滿足我們就可以使用'CASE' – Susang

回答

5

如果年將是這兩個,或一組有限的,你可以做到這一點與條件計數

select name, 
     sum(case when year(date) = 2014 then 1 else 0 end) as count_14, 
     sum(case when year(date) = 2015 then 1 else 0 end) as count_15 
from yourTable 
group by name 

否則,我會建議把今年的行,然後在演示其更改爲列層(或樞軸)

select name, year(date), count(*) 
from yourTable 
group by name, year(date) 
+0

正常工作去做,謝謝 –

+0

不客氣,g他幫助了! –