2017-05-30 88 views
0

我每年都會在每年4年的時間裏進行一次年度報告。在報告中顯示已有的年份選項將被報告。例如選擇2013-2016,所以在報告中從2013年,2014年,2015年和2016年 有關詳細信息顯示數據我有表象下面這樣:在列上獲得總和

+-----------------+--------------+-------------+-------------+ 
| id_jenis_perjal | jenis_perjal | id_tahun | tahun  | 
+-----------------+--------------+-------------+-------------+ 
|  7  | RPPJ   | 1   | 2013  | 
|  7  | RPPJ   | 1   | 2013  | 
|  7  | RPPJ   | 2   | 2014  | 
|  7  | RPPJ   | 3   | 2015  | 
|  7  | RPPJ   | 4   | 2016  | 
|  8  | Rambu  | 1   | 2013  | 
|  8  | Rambu  | 2   | 2014  | 
|  8  | Rambu  | 2   | 2014  | 
|  8  | Rambu  | 3   | 2015  | 
|  8  | Rambu  | 4   | 2016  | 
|  8  | Rambu  | 4   | 2016  | 
|  8  | Rambu  | 4   | 2016  | 
+-----------------+--------------+-------------+-------------+ 

但顯示的報告我不得不修改該表是這樣

+-----------------+------+------+------+------+ 
| jenis_perjal | 2013 | 2014 | 2015 | 2016 | 
+-----------------+------+------+------+------+ 
|  RPPJ  | 2 | 1 | 1 | 1 | 
|  Rambu  | 1 | 2 | 1 | 3 | 
+-----------------+------+------+------+------+ 
+0

搜索'groupby'&'count'在下面的mysql –

+0

而不是scaisEdge的回答,考慮處理應用程序代碼中的數據顯示問題(在本例中爲php) – Strawberry

+0

這被稱爲數據透視表,並且已經在這裏多次詢問和回答。重複的主題描述了在MySQL中的靜態(預先知道的列)和動態(列在動態確定)。請注意,在應用程序代碼中執行此轉換可能更有效,而不是在mysql中 - 正如@Strawberry也指出的那樣。 – Shadow

回答

1

您coulduse總和和組根據情況時

select jenis_perjal 
     , sum(case when tahum = 2013 then id_tahun end) as 2013 
     , sum(case when tahum = 2014 then id_tahun end) as 2014 
     , sum(case when tahum = 2015 then id_tahun end) as 2015 
     , sum(case when tahum = 2016 then id_tahun end) as 2016 
    from my_table 
    group by jenis_perjal