您没有指定您使用的 RDBMS,所以这里有两个解决方案。如果你有一个UNPIVOT
函数,然后是一个PIVOT
:
select *
from
(
select value, left(fields, 1) col,
substring(fields, 3, len(fields) -2) row
from yourtable
unpivot
(
value
for fields in(A_first, B_first, C_first,
A_second, B_second, C_second,
A_third, B_third, C_third)
) unpiv
) src
pivot
(
max(value)
for col in ([A], [B], [C])
) piv
请参阅带有演示的 SQL Fiddle
如果您没有UNPIVOT
andPIVOT
功能,那么您可以使用UNION ALL
:
select
max(case when col = 'A' then value end) A,
max(case when col = 'B' then value end) B,
max(case when col = 'C' then value end) C
from
(
select value, left(fields, 1) col, substring(fields, 3, len(fields) -2) row
from
(
select A_first value, 'A_first' fields
from yourtable
union all
select B_first value, 'B_first' fields
from yourtable
union all
select C_first value, 'C_first' fields
from yourtable
union all
select A_second value, 'A_second' fields
from yourtable
union all
select B_second value, 'B_second' fields
from yourtable
union all
select C_second value, 'C_second' fields
from yourtable
union all
select A_third value, 'A_third' fields
from yourtable
union all
select B_third value, 'B_third' fields
from yourtable
union all
select C_third value, 'C_third' fields
from yourtable
) unpiv
) src
group by row
请参阅带有演示的 SQL Fiddle
两者都会产生相同的结果:
| A | B | C |
-------------------
| 638 | 450 | 188 |
| 638 | 439 | 187 |
| 546 | 256 | 789 |
请注意,为了执行此任务,每列的数据类型必须相同。如果它们不是,那么您将需要convert
在UNPIVOT
.
这个答案做了一些假设:
- 现有列将始终以新列值开头(
A
、
B
或C
等)
- 现有列将始终以行号前的两个字符开头。