Du skal bruge betinget summering og dynamisk SQL til dette
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;
Output:
| NAME | APPLE | ORANGE | BANANA | KIWI | MANGO | ------------------------------------------------------ | James | (null) | (null) | (null) | (null) | 1 | | John | (null) | 2 | 3 | 1 | (null) | | Mary | 4 | 2 | (null) | (null) | (null) |
Her er SQLFiddle demo
Nu vil du ikke være i stand til at pakke det ind i en visning, men du kan gøre det til en lagret procedure.
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 ;
Og brug det sådan her:
CALL sp_order_report();
Her er SQLFiddle demo