如何编写MySQL动态数据透视表?

时间:2016-04-11 19:32:08

标签: mysql pivot

我无法理解MySQL中的数据透视表。

使用看起来像这样的SQL调用:

    SELECT DISTINCT year, type1, type2, type3, type4 FROM Table_08 WHERE iso2ltr = 'CO' AND city = 'Boulder' ORDER BY year DESC LIMIT 7

表格如下所示:

    year      |   type1     |   type2     |   type3     |   type4
    -----------------------------------------------------------------------
    2014      |   242       |     1       |   41        |   NULL
    2013      |   218       |     0       |   38        |   NULL
    2012      |   249       |     0       |   NULL      |  32
    2011      |   275       |     2       |   NULL      |   35
    2010      |   210       |     4       |   NULL      |   33
    2009      |   245       |     5       |   NULL      |   32
    2008      |   201       |     0       |   NULL      |   40

请注意,我需要订购年份DESC LIMIT 7.我的最新数据是2014年。

这就是我要找的:

    type   |   2014  |   2013  |   2012  |   2011   |   2010    |   2009   |   2008
    ---------------------------------------------------------------------------------------------------------------
    type1  |   242   |   218   |   249   |   275    |   210     |   245    |   201
    type2  |   1     |   0     |    0    |   2      |   4       |   5      |   0
    type3  |   41    |   38    |   NULL  |   NULL   |   NULL    |   NULL   |   NULL
    type4  |   NULL  |   NULL  |    32   |   35     |   33      |   32     |   40

这个SQL只给我一种类型,它不是动态的:

    SELECT city,  
        MAX( CASE WHEN YEAR =2014 THEN type1 END ) AS  '2014',
        MAX( CASE WHEN YEAR =2013 THEN type1 END ) AS  '2013',
        MAX( CASE WHEN YEAR =2012 THEN type1 END ) AS  '2012',
        MAX( CASE WHEN YEAR =2011 THEN type1 END ) AS  '2011',
        MAX( CASE WHEN YEAR =2010 THEN type1 END ) AS  '2010',
        MAX( CASE WHEN YEAR =2009 THEN type1 END ) AS  '2009',
        MAX( CASE WHEN YEAR =2008 THEN type1 END ) AS  '2008'
    FROM Table_08
    WHERE iso2ltr =  'CO' AND city =  'Boulder'
    GROUP BY city

我怎样才能列出所有类型,并且是动态的?

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

您可以使用GROUP_CONCAT返回以逗号分隔的列表,然后在代码中处理它。

SELECT GROUP_CONCAT(IFNULL(year,"NULL")),
       GROUP_CONCAT(IFNULL(type1,"NULL")),
       GROUP_CONCAT(IFNULL(type2,"NULL")),
       GROUP_CONCAT(IFNULL(type3,"NULL")),
       GROUP_CONCAT(IFNULL(type4,"NULL"))
FROM
(SELECT DISTINCT year, type1, type2, type3, type4 FROM Table_08 WHERE iso2ltr = 'CO' AND city = 'Boulder' ORDER BY year DESC LIMIT 7)as T