mysql数据透视表语法错误

时间:2014-01-24 03:10:31

标签: mysql pivot-table

mysql说我在这段代码上有语法错误。谁能告诉我它在哪里?

SET @sql = NULL;

SELECT GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE WHEN uploaddate = ''', uploaddate,
''' THEN points END) `', uploaddate, '`'))
INTO @sql
FROM prepress.imsexport;

SET @sql = CONCAT('SELECT uploadedby, ', @sql, ' 
FROM prepress.imsexport 
GROUP BY uploadedby');

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

我还想在uploaddate上使用date_format如何在不搞砸concat函数的情况下这样做?

1 个答案:

答案 0 :(得分:0)

  

mysql说我的代码有语法错误。谁能告诉我它在哪里?

乍一看,您的代码看起来很好。

  

*我还想在uploaddate上使用date_format如何在不搞砸concat函数的情况下这样做?*

如果每个日期每SUM()行可能有多行,则您很可能会使用MAX()而不是uploadedby

以下是您使用DATE_FORMAT()的代码看起来像

的方式
SET @sql = NULL;

SELECT GROUP_CONCAT(DISTINCT
CONCAT('SUM(CASE WHEN DATE(uploaddate) = ''', DATE(uploaddate),
''' THEN points END) `', DATE_FORMAT(uploaddate, '%m/%d/%Y'), '`'))
INTO @sql
FROM imsexport;

SET @sql = CONCAT('SELECT uploadedby, ', @sql, ' 
FROM imsexport 
GROUP BY uploadedby');

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

输出:

| UPLOADEDBY | 01/01/2013 | 01/02/2013 | 01/03/2013 | 01/04/2013 |
|------------|------------|------------|------------|------------|
|        Bob |          1 |          2 |          1 |          3 |
|        Sue |          4 |          2 |     (null) |          2 |

这是 SQLFiddle 演示


以下是使用mysql控制台执行它的方式

mysql> SET @sql = NULL;
Query OK, 0 rows affected (0.00 sec)

mysql> 
mysql> SELECT GROUP_CONCAT(DISTINCT
    -> CONCAT('SUM(CASE WHEN DATE(uploaddate) = ''', DATE(uploaddate),
    -> ''' THEN points END) `', DATE_FORMAT(uploaddate, '%m/%d/%Y'), '`'))
    -> INTO @sql
    -> FROM imsexport;
Query OK, 1 row affected (0.00 sec)

mysql> 
mysql> SET @sql = CONCAT('SELECT uploadedby, ', @sql, ' 
    '> FROM imsexport 
    '> GROUP BY uploadedby');
Query OK, 0 rows affected (0.00 sec)

mysql> 
mysql> PREPARE stmt FROM @sql;
Query OK, 0 rows affected (0.00 sec)
Statement prepared

mysql> EXECUTE stmt;
+------------+------------+------------+------------+------------+
| uploadedby | 01/01/2013 | 01/02/2013 | 01/03/2013 | 01/04/2013 |
+------------+------------+------------+------------+------------+
| Bob        |          1 |          2 |          1 |          3 |
| Sue        |          4 |          2 |       NULL |          2 |
+------------+------------+------------+------------+------------+
2 rows in set (0.01 sec)

mysql> DEALLOCATE PREPARE stmt;
Query OK, 0 rows affected (0.00 sec)