MySQL Query用于更改表格方向(垂直于水平)

时间:2018-04-01 14:10:52

标签: mysql sql pivot-table

所以我有这张桌子:

Year | MonthInterval | RainfallIndex
2016 | Jan-Feb       | 1.03
2016 | Feb-Mar       | 0.23
2016 | Mar-Apr       | 2.30

我可以应用什么查询将表格转换为:

Year | Jan-Feb | Feb-Mar | Mar-Apr 
2016 | 1.03    | 0.23    | 2.30 

1 个答案:

答案 0 :(得分:1)

您可以使用案例陈述:

   CREATE TABLE rainfall_pivot AS
  SELECT
    Year,
    sum(CASE WHEN MONTH(MonthInterval) = 'Jan-Feb'
      THEN RainfallIndex
        ELSE 0 END) AS "Jan-Feb",
    sum(CASE WHEN MONTH(MonthInterval) = 'Feb-Mar'
      THEN RainfallIndex
        ELSE 0 END) AS "Feb-Mar",
    sum(CASE WHEN MONTH(MonthInterval) = 'Mar-Apr'
      THEN RainfallIndex
        ELSE 0 END) AS "Mar-Apr"
  FROM your_table
  GROUP BY 1
  ORDER BY 1;