gpt4 book ai didi

mysql - SQL创建矩阵表

转载 作者:行者123 更新时间:2023-11-29 13:41:33 27 4
gpt4 key购买 nike

我想在 MySQL 中创建一个由 3 个表生成的 View 。

请参阅下表。

我想做的就是创建一个 View ,使用 table:ItemList 的 col:name 作为新 View 的列的标签。

如何使用 SQL 实现此目的?

表:ItemList,这个变化太频繁了

+----+-------------+
| id | name |
+----+-------------+
| 1 | Apple |
| 2 | Orange |
| 3 | Banana |
| 4 | Kiwi |
| 5 | Mango |
+----+-------------+

表:UserList

+----+-------------+
| id | name |
+----+-------------+
| 1 | John |
| 2 | Mary |
| 3 | James |
+----+-------------+

表: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

+-------+-------+--------+--------+------+-------+
| User | Apple | Orange | Banana | Kiwi | Mango |
+-------+-------+--------+--------+------+-------+
| John | | 2 | 3 | 1 | |
| Mary | 4 | 2 | | | |
| James | | | | | 1 |
+-------+-------+--------+--------+------+-------+

最佳答案

为此,您必须使用条件求和和动态 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;

输出:

|  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 ;

并像这样使用它:

CALL sp_order_report();

这里是SQLFiddle 演示

关于mysql - SQL创建矩阵表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18010870/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com