带有concat的MySQL动态数据透视表

时间:2016-01-16 19:22:26

标签: mysql sql

大家早上好,

我有一个名为salesData的视图,它基本上看起来像这样,我想动态地转动它,因为它可能会在以后更新。

+-------------+------------+------+
| salesTotal  | salesYear  |      |
+-------------+------------+------+
|    3016207  |       2008 |      |
|    3079627  |       2009 |      |
|    3133681  |       2010 |      |
|    3102944  |       2011 |      |
|    3126710  |       2012 |      |
|    3123600  |       2013 |      |
|    3116452  |       2014 |      |
|    3175186  |       2015 |      |
|     122371  |       2016 |
+-------------+------------+------+

我设计了以下查询,但它似乎无法正常工作。 MySQL工作台给我一个奇怪的错误信息:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' MAX(CASE WHEN salesYear='2008 THEN 3016207 ELSE 0 END) AS 2008,MAX(CASE WHEN sa' at line 1

我的查询如下:

SET @sql = NULL;
SELECT 
    GROUP_CONCAT(DISTINCT CONCAT('MAX(CASE WHEN salesYear=''',salesYear,''' THEN ',salesTotal, ' ELSE 0 END) AS ',salesYear))
INTO @sql 
FROM salesData;

SET @sql = CONCAT('SELECT, ', @sql, ' FROM salesData');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

如果有人能给我一个提示,我将不胜感激。非常感谢:))

哦,顺便说一句,我正在寻找的结果是:

|    2008 |    2009 |    2010 |    2011 |    2012 |    2013 |    2014 |    2015 |  |
+---------+---------+---------+---------+---------+---------+---------+---------+--+
| 3133681 | 3133681 | 3133681 | 3102944 | 3126710 | 3126710 | 3126710 | 3126710 |  |
+---------+---------+---------+---------+---------+---------+---------+---------+--+

我使用以下查询得到它,但这个问题的重点是使查询动态化;)):

SELECT
  MAX(CASE WHEN (salesYear='2010') THEN salesTotal ELSE 0 END) AS '2008',
  MAX(CASE WHEN (salesYear='2010') THEN salesTotal ELSE 0 END) AS '2009',
  MAX(CASE WHEN (salesYear='2010') THEN salesTotal ELSE 0 END) AS '2010',
  MAX(CASE WHEN (salesYear='2011') THEN salesTotal ELSE 0 END) AS '2011',
  MAX(CASE WHEN (salesYear='2012') THEN salesTotal ELSE 0 END) AS '2012',
  MAX(CASE WHEN (salesYear='2012') THEN salesTotal ELSE 0 END) AS '2013', 
  MAX(CASE WHEN (salesYear='2012') THEN salesTotal ELSE 0 END) AS '2014', 
  MAX(CASE WHEN (salesYear='2012') THEN salesTotal ELSE 0 END) AS '2015', 
  MAX(CASE WHEN (salesYear='2012') THEN salesTotal ELSE 0 END) AS '2016' 
  FROM salesData
编辑:我发现了错误。此表达式中的salesYear未正确连接。

GROUP_CONCAT(DISTINCT CONCAT('MAX(CASE WHEN salesYear=''',salesYear,''' THEN ',salesTotal, ' ELSE 0 END) AS ',salesYear))

当我用字符串值替换它时,如下所示,查询工作正常。任何人都知道如何将salesYear变量放在单引号之间?

 GROUP_CONCAT(DISTINCT CONCAT('MAX(CASE WHEN salesYear=''',salesYear,''' THEN ',salesTotal, ' ELSE 0 END) AS ','test'))

1 个答案:

答案 0 :(得分:0)

CONCAT(''',salesYear,'“')有效。似乎单引号不起作用:)