数据透视表出错

时间:2015-07-10 09:07:47

标签: mysql sql pivot

我有一个SQL查询来显示有关公司的信息。其中一列称为PieceType,公司可以有多种类型,每种类型都有一个数量。所以我想将每个片段类型显示为一列,然后显示其下的数量。所以每种类型都有自己的列。

所以它看起来像这样:

enter image description here

我在这里创建了一个示例数据库:http://www.sqlfiddle.com/#!9/13230/4

SET group_concat_max_len=4294967294;
SET @COLUMNS = NULL;

/* Build columns to pivot */

SELECT GROUP_CONCAT(
        DISTINCT CONCAT(
            'CASE WHEN jp.PieceType = "', 
            jp.PieceType ,
            '" THEN 1 ELSE NULL END AS ',
            jp.PieceType
        )
) INTO @COLUMNS
FROM job_pieces jp;

/* Build full query */
SET @SQL = CONCAT(
        'SELECT    
                c.Name,
                ',@COLUMNS'
        FROM customer c
        LEFT JOIN job_new jn ON c.JobID = jn.ID
        LEFT JOIN job_pieces jp ON c.JobID = jp.JobID
        WHERE c.Company_ID = 123
        GROUP BY c.ID'
);

/* Prepare and execute the query*/
PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

但是当我运行查询时,我收到此错误:

  

调用本机函数'CONCAT'时的参数不正确

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题导致一些问题。

首先,设置@SQL的代码缺少CONCAT函数的逗号:

SET @SQL = CONCAT(
        'SELECT    
                c.Name,
                ',@COLUMNS, '
                       -- ^ this is missing  
        FROM customer c
        LEFT JOIN job_new jn ON c.JobID = jn.ID
        LEFT JOIN job_pieces jp ON c.JobID = jp.JobID
        WHERE c.Company_ID = 123
        GROUP BY c.Name'
);

添加该逗号后,您将收到另一个错误:

  

您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在'CASE,CASE WHEN jp.PieceType =“CTN”附近使用正确的语法,然后将1个ELSE NULL END作为CTN,在第3行jp.Pie'时使用

此错误是因为您的代码获取列列表。由于您的jp.PieceType值为CASE,这是一个保留字,因此语法失败。您需要转义列名称的别名:

SELECT GROUP_CONCAT(
        DISTINCT CONCAT(
            'CASE WHEN jp.PieceType = ''', 
            jp.PieceType ,
            ''' THEN 1 ELSE NULL END AS `',
                                     -- ^ add this
            jp.PieceType, '`'
                     -- ^ add this after the comma
        )
) INTO @COLUMNS
FROM job_pieces jp;

这是一个sql fiddle代码现在正在运行。但是,我还必须注意到,您缺少围绕CASE表达式的聚合函数。通常,当您像这样PIVOT数据时,您使用聚合函数,如MAX / MIN / SUM等。如果您希望总计Qty PieceType },那么您似乎想要使用SUM,因此您的代码将是:

SET group_concat_max_len=4294967294;
SET @COLUMNS = NULL;


/* Build columns to pivot */
SELECT GROUP_CONCAT(
        DISTINCT CONCAT(
            'SUM(CASE WHEN jp.PieceType = ''', 
            jp.PieceType ,
            ''' THEN jp.QTY ELSE 0 END) AS `',
            jp.PieceType, '`'
        )
) INTO @COLUMNS
FROM job_pieces jp;

/* Build full query */
SET @SQL = CONCAT(
        'SELECT    
                c.Name,
                ',@COLUMNS, '
        FROM customer c
        LEFT JOIN job_new jn ON c.JobID = jn.ID
        LEFT JOIN job_pieces jp ON c.JobID = jp.JobID
        WHERE c.Company_ID = 123
        GROUP BY c.Name'
);

/* Prepare and execute the query*/
PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

请参阅SQL Fiddle with Demo