在SQL / PHP中将行转置为列

时间:2019-05-21 00:25:23

标签: mysql sql

我获取了以下数据:

MONTH      |      TOTAL
-------------------------
Jan        |      100
Feb        |      200
Mar        |      300

使用此查询:

$query = "SELECT DATE_FORMAT(date,'%b') AS MONTH, SUM(col1+col2) AS TOTAL FROM myTable GROUP BY YEAR(date),MONTH(date)";

如何编辑以上查询或重写以获得以下结果:

JAN | FEB | MAR
-------------------------
100 | 200 | 300

我经历了几乎所有其他类似的帖子。但是,对我来说,sql转置非常令人困惑。任何输入都非常感谢!

1 个答案:

答案 0 :(得分:2)

您可以使用条件聚合。以下将在SQL Server或MySQL中工作:

select year(date),
       sum(case when month(date) = 1 then col1 + col2 else 0 end) as jan,
       sum(case when month(date) = 2 then col1 + col2 else 0 end) as feb,
       sum(case when month(date) = 3 then col1 + col2 else 0 end) as mar
from mytable
group by year(date)
order by year(date); 

编辑(关于评论):

select year(date),
       sum(case when month(date) = 1 then val else 0 end) as jan,
       sum(case when month(date) = 2 then val else 0 end) as feb,
       sum(case when month(date) = 3 then val else 0 end) as mar
from (select t.*, (col1 + col2) as val
      from mytable
     ) t
group by year(date)
order by year(date);