2014-11-05 150 views
2

所以我有一個像這樣的tbl_total。選擇具有相似名稱的行

Name | Total | Month 
========================= 
David | 87  | Jan 
Mike | 67  | Jan 
David | 90  | Feb 
Mike | 100 | Feb 

我想這樣顯示它。可以請別人告訴我如何做到這一點因爲我不知道如何在PHP中這樣顯示。

Name | Jan | Feb 
=================== 
David | 87 | 90 
Mike | 67 | 100 
+0

你可以展示你已有的東西嗎?另外爲什麼你不把重複(My)SQL? – 2014-11-05 12:14:46

+0

Google:「mysql pivot」。 – 2014-11-05 12:15:34

+0

谷歌搜索「MySQL的樞軸」帶回到StackOverFlow http://stackoverflow.com/questions/7674786/mysql-pivot-table – Yang 2014-11-05 12:16:39

回答

7
select name, 
     sum(case when month = 'Jan' then total else 0 end) as Jan, 
     sum(case when month = 'Feb' then total else 0 end) as Feb, 
     sum(case when month = 'Mar' then total else 0 end) as Mar, 
     sum(case when month = 'Apr' then total else 0 end) as Apr, 
     sum(case when month = 'May' then total else 0 end) as May, 
     sum(case when month = 'Jun' then total else 0 end) as Jun, 
     sum(case when month = 'Jul' then total else 0 end) as Jul, 
     sum(case when month = 'Aug' then total else 0 end) as Aug, 
     sum(case when month = 'Sep' then total else 0 end) as Sep, 
     sum(case when month = 'Oct' then total else 0 end) as Oct, 
     sum(case when month = 'Nov' then total else 0 end) as Nov, 
     sum(case when month = 'Dec' then total else 0 end) as `Dec` 
from your_table 
group by name 
+0

你不能,但你可以接受這個答案..這是一樣的2 upvotes;) – Naruto 2014-11-05 12:19:30

+0

@Naruto:他不是OP。可能很難接受它;) – 2014-11-05 12:20:27

+0

噢,對不起,我的壞。無論如何,我會upvote你爲他;) – Naruto 2014-11-05 12:21:21

0

試試這個..

Select Name,SUM(Total), 
SUM(case when Month = 'Jan' then total else 0 end) as Jan, 
SUM(case when Month = 'Feb' then total else 0 end) as Feb 
from tbl_total 
group by Name 

重複Case語句不同月份的需要。