2012-04-03 42 views
2

我有一個MySQL數據庫,看起來像這樣:MySQL的單元格值的日期作爲新列具有多年

|id | city | created | 
|1 | city1 |2011-12-10 | 
|2 | city2 |2010-02-01 | 
|3 | city3 |2009-12-03 | 
|4 | city1 |2012-11-16 | 
|5 | city2 |2012-08-03 | 
|6 | city3 |2011-10-01 | 
|7 | city1 |2009-10-02 | 
|8 | city2 |2011-12-01 | 
|9 | city3 |2012-06-30 | 

但我想有一個看起來像這樣

|city | 2009 | 2010 | 2011 | 2012 | 
|city1 | 1 | 0 | 1 | 1 | 
|city2 | 0 | 1 | 1 | 1 | 
|city3 | 1 | 1 | 0 | 1 | 
+0

SELECT COUNT(ID)AS GROUP BY城市 我有問題要分開年不同列的要求,城市,YEAR(創建)截至今年 FROM查詢。我實際上不知道該怎麼做 – jocken 2012-04-03 07:44:54

回答

1

也許是這樣的:

SELECT 
    YourTable.city, 
    SUM(IF(YEAR(created)=2009,1,0)) AS '2009', 
    SUM(IF(YEAR(created)=2010,1,0)) AS '2010', 
    SUM(IF(YEAR(created)=2011,1,0)) AS '2011', 
    SUM(IF(YEAR(created)=2012,1,0)) AS '2012' 
FROM 
    YourTable 
GROUP BY 
    YourTable.city 
+0

如果你在AS之前加了一個圓括號但是它不是很動態的話,這種方法就行得通了。是否有可能自動檢測一年是否存在併爲其創建一列? – jocken 2012-04-03 07:59:32

+0

我認爲只能用動態sql。如果您使用MSSQL 2005+,這將非常容易。 – Arion 2012-04-03 08:02:37

0
備用表或視圖

嘗試以下操作:

select 
    city, 
    sum(case when year(created) = 2009 then 1 else 0 end) as 2009, 
    sum(case when year(created) = 2010 then 1 else 0 end) as 2010, 
    sum(case when year(created) = 2011 then 1 else 0 end) as 2011, 
    sum(case when year(created) = 2012 then 1 else 0 end) as 2012 
from 
    enquiries 
group by city 
相關問題