Reputation: 811
I want to make a view in MySQL that will be generated from 3 tables.
Please see the following tables.
All I want to do is to create a view, using col:name of table:ItemList as the labels of the columns of the new view.
How can I achieve this using SQL?
table: ItemList ,this changes so frequently
+----+-------------+
| id | name |
+----+-------------+
| 1 | Apple |
| 2 | Orange |
| 3 | Banana |
| 4 | Kiwi |
| 5 | Mango |
+----+-------------+
table: UserList
+----+-------------+
| id | name |
+----+-------------+
| 1 | John |
| 2 | Mary |
| 3 | James |
+----+-------------+
table: OrderList
+----+------+------+-----+
| id | User | Item | qty |
+----+------+------+-----+
| 1 | 1 | 4 | 1 |
| 2 | 1 | 2 | 2 |
| 3 | 2 | 1 | 4 |
| 4 | 1 | 3 | 3 |
| 5 | 3 | 5 | 1 |
| 6 | 2 | 2 | 2 |
+----+------+------+-----+
view that I want to create
+-------+-------+--------+--------+------+-------+
| User | Apple | Orange | Banana | Kiwi | Mango |
+-------+-------+--------+--------+------+-------+
| John | | 2 | 3 | 1 | |
| Mary | 4 | 2 | | | |
| James | | | | | 1 |
+-------+-------+--------+--------+------+-------+
Upvotes: 0
Views: 3821
Reputation: 92805
You have to use conditional summation and dynamic SQL for this
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) |
Here is SQLFiddle demo
Now you won't be able to wrap it into a view, but you can make it a stored 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 ;
And use it like this:
CALL sp_order_report();
Here is SQLFiddle demo
Upvotes: 2