結果を取得する方法はいくつかありますが、いずれもrow_number
データの各行のシーケンスを生成するために使用されます。
CASE 式で集計関数を使用できます。
select
max(case when seq = 1 then columna end) columna_1,
max(case when seq = 1 then columnb end) columnb_1,
max(case when seq = 1 then columnc end) columnc_1,
max(case when seq = 2 then columna end) columna_2,
max(case when seq = 2 then columnb end) columnb_2,
max(case when seq = 2 then columnc end) columnc_2,
max(case when seq = 3 then columna end) columna_3,
max(case when seq = 3 then columnb end) columnb_3,
max(case when seq = 3 then columnc end) columnc_3
from
(
select columna, columnb, columnc,
row_number() over(order by columna) seq
from yourtable
) d;
SQL Fiddle with Demoを参照してください。
PIVOT 関数を使用できますが、最初に 3 列のデータのピボットを解除してから、PIVOT を適用する必要があります。アンピボット プロセスにより、3 列のデータが複数の行に変換されます。UNPIVOT 関数または CROSS APPLY を使用して、これを実行できます。
select ColumnA_1, ColumnB_1, ColumnC_1,
ColumnA_2, ColumnB_2, ColumnC_2,
ColumnA_3, ColumnB_3, ColumnC_3
from
(
select col = col+'_'+cast(seq as varchar(10)),
value
from
(
select columna, columnb, columnc,
row_number() over(order by columna) seq
from yourtable
) d
cross apply
(
select 'ColumnA', columna union all
select 'ColumnB', columnb union all
select 'ColumnC', columnc
) c (col, value)
) s
pivot
(
max(value)
for col in (ColumnA_1, ColumnB_1, ColumnC_1,
ColumnA_2, ColumnB_2, ColumnC_2,
ColumnA_3, ColumnB_3, ColumnC_3)
) piv;
SQL Fiddle with Demoを参照してください。上記の 2 つのバージョンは、限られた数または既知の値がある場合にうまく機能しますが、未知の数がある場合は、動的 SQL を使用して最終結果を取得する必要があります。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(col+'_'+cast(seq as varchar(10)))
from
(
select row_number() over(order by columna) seq
from yourtable
) d
cross apply
(
select 'ColumnA', 1 union all
select 'ColumnB', 2 union all
select 'ColumnC', 3
) c (col, so)
group by col, seq, so
order by seq, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + '
from
(
select col = col+''_''+cast(seq as varchar(10)),
value
from
(
select columna, columnb, columnc,
row_number() over(order by columna) seq
from yourtable
) d
cross apply
(
select ''ColumnA'', columna union all
select ''ColumnB'', columnb union all
select ''ColumnC'', columnc
) c (col, value)
) x
pivot
(
max(value)
for col in (' + @cols + ')
) p '
execute sp_executesql @query;
SQL Fiddle with Demoを参照してください。すべてのバージョンで結果が得られます。
| COLUMNA_1 | COLUMNB_1 | COLUMNC_1 | COLUMNA_2 | COLUMNB_2 | COLUMNC_2 | COLUMNA_3 | COLUMNB_3 | COLUMNC_3 |
| P | Q | R | S | T | U | V | W | X |