gpt4 book ai didi

MySQL 存储过程或动态 View

转载 作者:行者123 更新时间:2023-11-30 00:19:08 25 4
gpt4 key购买 nike

我有以下准备好的语句来跨三个表运行动态数据透视查询

SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT(
'max(case when division_id = ', dp.division_id, ' then process_name end) AS ', d.division_shortName, ' '
)
) INTO @sql
FROM
erp_divisionProcess dp LEFT JOIN erp_division d ON d.division_id = dp.division_id;
SET @sql = concat('SELECT ', @sql, 'FROM (
SELECT d.division_id, p.process_name, X.rnk
FROM erp_division d
LEFT JOIN (SELECT dp.division_id, dp.process_id, (SELECT COUNT(*) FROM erp_divisionProcess A WHERE dp.division_id = A.division_id AND dp.process_id < A.process_id) AS rnk
FROM erp_divisionProcess dp) X ON X.division_id = d.division_id
LEFT JOIN erp_BusinessProcess p ON p.process_id = X.process_id
) x
GROUP BY rnk');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

它会生成如下所示的旋转数据集:

+-----------------+-----------------+------------+------------+--------------+------------+------------+-------+
| PBL | PLI | PMI | PBT | PBP | PBI | PBTL | PRDT |
+-----------------+-----------------+------------+------------+--------------+------------+------------+-------+
| Sales | Human Resources | Production | Purchasing | Sales | Purchasing | Purchasing | Sales |
| Human Resources | Purchasing | NULL | NULL | Purchasing | NULL | NULL | NULL |
| Purchasing | Finance | NULL | NULL | Distribution | NULL | NULL | NULL |
| Distribution | NULL | NULL | NULL | Production | NULL | NULL | NULL |
| Production | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| Finance | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
+-----------------+-----------------+------------+------------+--------------+------------+------------+-------+

我希望生成的数据集可以提取到 Excel 中,但当我尝试运行完整语句时,MS Query 会抛出错误。我相信我无法从准备好的语句创建 View ,那么如何才能获得可用的查询结果,而不必每次都重新输入(复制和粘贴)它并从 MySQL 中获取结果。

谢谢!

最佳答案

I believe I can't create a view from the prepared statement, so how can I have the query result available without having to retype (copy and paste)

您可以使用准备好的查询创建 View

尝试在代码中进行以下更改:

-- SET @sql = concat('SELECT ', @sql, 'FROM (
SET @sql = concat( 'CREATE VIEW view_name AS SELECT ', @sql, ' FROM (
SELECT d.division_id, p.process_name, X.rnk
FROM erp_division d
LEFT JOIN (SELECT dp.division_id, dp.process_id,
(SELECT COUNT(*) FROM erp_divisionProcess A
WHERE dp.division_id = A.division_id
AND dp.process_id < A.process_id) AS rnk
FROM erp_divisionProcess dp) X
ON X.division_id = d.division_id
LEFT JOIN erp_BusinessProcess p ON p.process_id = X.process_id
) Y
GROUP BY rnk');

创建 View 后,您可以发出 select * from view_name 将数据提取到客户端。

演示 @ MySQL 5.5.32 Fiddle

关于MySQL 存储过程或动态 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23389333/

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