I have this table of product data:
+--------+--------+------------+
| item_id| amount | date |
+--------+--------+------------+
| 4 | 100 | 01-04-2020 |
| 6 | 200 | 01-04-2020 |
| 9 | 300 | 01-04-2020 |
| 4 | 400 | 01-04-2020 |
| 4 | 300 | 02-04-2020 |
| 6 | 150 | 02-04-2020 |
| 6 | 150 | 02-04-2020 |
| 9 | 700 | 02-04-2020 |
+--------+--------+------------+
I want to make a query which pivots this table so that the ItemId
is on the column side, which displays the sum amount of all the items:
+------------+-----+-----+-----+
| date | 4 | 6 | 9 |
+------------+-----+-----+-----+
| 01-04-2020 | 400 | 200 | 400 |
| 02-04-2020 | 300 | 300 | 700 |
+------------+-----+-----+-----+
I was able to write a query that could do it:
SELECT
date,
SUM(IF(item_id = '1', item_record.amount, NULL)) AS 1,
SUM(IF(item_id = '2', item_record.amount, NULL)) AS 2,
SUM(IF(item_id = '3', item_record.amount, NULL)) AS 3,
COUNT(*) AS Total
FROM item_record
GROUP BY date WITH ROLLUP
But the query was hardcoded to only display the columns with item_id
1, 2, and 3. I need to make it dynamic.
Searching around StackOverflow, I encountered this question. Following the accepted answer, I tried making it into a prepared statement
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(IF(item_record.item_id = "',item_record.item_id,'", item_record.amount, NULL))
AS ',item_record.item_id
)
) INTO @sql
FROM item_record;
SET @sql =
CONCAT('SELECT date,
',@sql,',
COUNT(*) AS Total
FROM item_record
GROUP BY date WITH ROLLUP
');
PREPARE stmt FROM @sql;
EXECUTE stmt;
But I encountered an error:
SQL Error [1064] [42000]: 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
'4,SUM(IF(item_record.item_id = "6", item_record.amount, NULL)) AS 6' at line 2
Where did I do wrong? This looks like a mere syntax error, but I've been at this for hours and I still didn't know what's up.