# ピボットテーブルのエントリ

``````R_Id    M_ID      Y_ID  Value
100000  1          1    10
100000  1          2    20
100000  1          3    30
100001  1          1    10
100001  1          2    20
100001  1          3    30
100002  1          1    10
100002  1          2    20
100002  1          3    30
``````

``````  100000   1   1    10  1    2    20   1   3   30
100001   1   1    10  1    2    20   1   3   30
100002   1   1    10  1    2    20   1   3   30
``````

0
こんにちは@MichałPowaga、これは動作します。 whileループが使用されているので、パフォーマンスの問題を感じるかもしれません

さて、ガード。どうもありがとう

こんにちは、私の答えをテストしましたか？

この場合ではありません。ここでwhileループは、行ごとにデータを処理しないように、のみ（最後に実行される）クエリを作成するために使用されます。

## 1 答え

``````if object_id('tempdb..#t') is not null drop table #t

select * into #t from (
select 100000 as r_id, 1 as m_id, 1 as y_id, 10 as val union
select 100000, 1, 2, 20 union select 100000, 1, 3, 30 union
select 100001, 1, 1, 10 union select 100001, 1, 2, 20 union
select 100002, 1, 1, 10 union select 100002, 1, 2, 20 union
select 100002, 1, 3, 30
) t

if object_id('tempdb..#tab') is not null drop table #tab

select r_id, m_id, y_id, val, row_number() over (partition by r_id order by r_id, m_id, y_id) as row_num
into #tab
from #t

declare @qt int, @q nvarchar(max), @i int, @qj nvarchar(max)

select top 1 @qt = count(*) from #tab group by r_id order by count(*) desc

set @q = 'select t.r_id'
set @qj = ' from (select distinct r_id from #tab) t'

set @i = 1
while @i <= @qt
begin
set @q = @q + ', t' + cast(@i as varchar) + '.m_id, t' + cast(@i as varchar) + '.y_id, t' + cast(@i as varchar) + '.val'
set @qj = @qj + ' left join #tab t' + cast(@i as varchar) + ' on t' + cast(@i as varchar) + '.r_id = t.r_id and t' + cast(@i as varchar) + '.row_num = '
if @i = 1 set @qj = @qj + '1'
else set @qj = @qj + 't'+cast(@i -1 as varchar)+'.row_num + 1'
set @i = @i + 1
end

set @q = @q + @qj

exec sp_executesql @q
``````
0