选择具有相似名称的行

时间:2014-11-05 12:12:03

标签: php mysql select

所以我有一个像这样的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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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语句。

相关问题