MySQL dynamic-pivot(MySQL 动态枢轴)
问题描述
我有一张像这样的产品零件表:
I have a table of product parts like this:
零件
part_id part_type product_id
--------------------------------------
1 A 1
2 B 1
3 A 2
4 B 2
5 A 3
6 B 3
而且我想要一个返回这样的表的查询:
and I want a query that will return a table like this:
product_id part_A_id part_B_id
----------------------------------------
1 1 2
2 3 4
3 5 6
在其实际实施中将有数百万个产品部件
In its actual implementation there will be millions of product parts
推荐答案
不幸的是,MySQL 没有 PIVOT
函数,但您可以使用聚合函数和 CASE
对其进行建模代码> 语句.对于动态版本,您将需要使用准备好的语句:
Unfortunately, MySQL does not have a PIVOT
function but you can model it using an aggregate function and a CASE
statement. For a dynamic version, you will need to use prepared statements:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when part_type = ''',
part_type,
''' then part_id end) AS part_',
part_type, '_id'
)
) INTO @sql
FROM
parts;
SET @sql = CONCAT('SELECT product_id, ', @sql, '
FROM parts
GROUP BY product_id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
参见SQL Fiddle with Demo
如果您只有几列,那么您可以使用静态版本:
If you had only a few columns, then you can use a Static version:
select product_id,
max(case when part_type ='A' then part_id end) as Part_A_Id,
max(case when part_type ='B' then part_id end) as Part_B_Id
from parts
group by product_id
这篇关于MySQL 动态枢轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL 动态枢轴


- 导入具有可变标题的 Excel 文件 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- SQL 临时表问题 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01