让我直接谈谈一个具体的例子。我有一个看起来像这样的表:
id,john,jack,jimy
1,22,NULL,NULL
2,NULL,55,66
我想知道是否可以使用sql将该表更改为下表:
id,person,value
1,john,22
2,jack,55
3,jimy,66
答案 0 :(得分:1)
如果您使用的是SQL Server,则可以使用UNPIVOT:
select ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), VALUE, PERSON
from Table1
unpivot (value for person in (john,jack,jimy)) A
<强>更新强>
当我提供此解决方案时,没有标签可以指导我。我不认为这个解决方案适用于MySQL,那么你可以尝试:
select 1, 'John' Person, max(John) Value from Table1 UNION
select 2, 'Jack' Person, max(Jack) Value from Table1 UNION
select 3, 'Jimy' Person, max(Jimy) Value from Table1
所示
答案 1 :(得分:0)
便携式SQL:
select 1 as id, 'john' as person, max(john) as value from yourtable
union all
select 2 as id, 'jack' as person, max(jack) as value from yourtable
union all
select 3 as id, 'jimy' as person, max(jimy) as value from yourtable
如果任何列中有多个非NULL值,请将max
替换为您选择的聚合。