Musisz do tego użyć sumowania warunkowego i dynamicznego 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;
Wyjście:
| NAME | APPLE | ORANGE | BANANA | KIWI | MANGO | ------------------------------------------------------ | James | (null) | (null) | (null) | (null) | 1 | | John | (null) | 2 | 3 | 1 | (null) | | Mary | 4 | 2 | (null) | (null) | (null) |
Oto SQLFiddle demo
Teraz nie będziesz w stanie zapakować go w widok, ale możesz zrobić z niego procedurę składowaną.
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 ;
I użyj go w ten sposób:
CALL sp_order_report();
Oto SQLFiddle demo