Devi usare la somma condizionale e l'SQL dinamico per questo
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;
Uscita:
| NAME | APPLE | ORANGE | BANANA | KIWI | MANGO | ------------------------------------------------------ | James | (null) | (null) | (null) | (null) | 1 | | John | (null) | 2 | 3 | 1 | (null) | | Mary | 4 | 2 | (null) | (null) | (null) |
Ecco SQLFiddle demo
Ora non sarai in grado di racchiuderlo in una vista, ma puoi renderlo una procedura memorizzata.
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 ;
E usalo in questo modo:
CALL sp_order_report();
Ecco SQLFiddle demo