ID | a | b | c
1 | a1 | b1 | c1
2 | a2 | b2 | c2
如何将行重新组织为 ID
、columntitle
、value
?
1 | a1 | a
1 | b1 | b
1 | c1 | c
2 | a2 | a
2 | b2 | b
2 | c2 | c
最佳答案
您正在尝试反透视 数据。 MySQL 没有 unpivot 函数,因此您必须使用 UNION ALL
查询将列转换为行:
select id, 'a' col, a value
from yourtable
union all
select id, 'b' col, b value
from yourtable
union all
select id, 'c' col, c value
from yourtable
参见 SQL Fiddle with Demo .
这也可以使用 CROSS JOIN
来完成:
select t.id,
c.col,
case c.col
when 'a' then a
when 'b' then b
when 'c' then c
end as data
from yourtable t
cross join
(
select 'a' as col
union all select 'b'
union all select 'c'
) c
关于MySQL - 如何将列转为行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50121830/