K tomu musíte použít podmíněný součet a dynamické SQL
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE WHEN l.Item = ',
id,
' THEN l.qty END) `',
name, '`'
)
) INTO @sql
FROM ItemLIst;
SET @sql = CONCAT('SELECT u.name, ', @sql, '
FROM OrderList l JOIN UserList u
ON l.User = u.id
GROUP BY u.name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Výstup:
| NAME | APPLE | ORANGE | BANANA | KIWI | MANGO | ------------------------------------------------------ | James | (null) | (null) | (null) | (null) | 1 | | John | (null) | 2 | 3 | 1 | (null) | | Mary | 4 | 2 | (null) | (null) | (null) |
Zde je SQLFiddle demo
Nyní jej nebudete moci zabalit do pohledu, ale můžete z něj vytvořit uloženou proceduru.
DELIMITER $$
CREATE PROCEDURE sp_order_report()
BEGIN
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE WHEN l.Item = ',
id,
' THEN l.qty END) `',
name, '`'
)
) INTO @sql
FROM
ItemLIst;
SET @sql = CONCAT('SELECT u.name, ', @sql, '
FROM OrderList l JOIN UserList u
ON l.User = u.id
GROUP BY u.name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
A použijte to takto:
CALL sp_order_report();
Zde je SQLFiddle demo