使用しているRDBMSを指定しなかったため、ここに2つの解決策があります。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 FiddlewithDemoを参照してください
UNPIVOTandPIVOT関数がない場合は、次を使用できます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 FiddlewithDemoを参照してください
どちらも同じ結果になります。
| A | B | C |
-------------------
| 638 | 450 | 188 |
| 638 | 439 | 187 |
| 546 | 256 | 789 |
このタスクを実行するには、データ型が各列で同じである必要があることに注意してください。そうでない場合は、convertの前に最初にデータを取得する必要がありますUNPIVOT。
この答えはいくつかの仮定をします:
- 既存の列は常に新しい列の値(
A、、、
BなどC)で始まります
- 既存の列は常に行番号の前の2文字で始まります。