I have an SQL query to display information about companies. One of the columns is called PieceType and a company could have many piece types and each type has a quantity. So I want to display each piece type as a column, then the quantity under it. So each type has its own column.
So it will look like this:
I've created a sample database 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;
But I'm getting this error when I run the query:
Incorrect parameters in the call to native function 'CONCAT'