この結果を得るには、いくつかの方法でクエリを作成できます。
partId
との値の数が限られている場合は、集計関数と CASE の組み合わせcardNumber
を使用できます。row_number()
select partid, cardnumber,
max(case when rn = 1 then rdrgrpid end) rdrgrpid_1,
max(case when rn = 1 then TZID end) TZID_1,
max(case when rn = 2 then rdrgrpid end) rdrgrpid_2,
max(case when rn = 2 then TZID end) TZID_2,
max(case when rn = 3 then rdrgrpid end) rdrgrpid_3,
max(case when rn = 3 then TZID end) TZID_3
from
(
select partId, cardNumber, RdrGrpID, TZID
, row_number() over(partition by partiD, cardnumber
order by rdrgrpid) rn
from yt
) d
group by partid, cardnumber;
デモで SQL Fiddle を参照してください
PIVOT/UNPIVOT 関数を使用して結果を取得することもできます。
select *
from
(
select partid, cardnumber,
col+'_'+cast(rn as varchar(10)) col,
val
from
(
select partId, cardNumber, RdrGrpID, TZID
, row_number() over(partition by partiD, cardnumber
order by rdrgrpid) rn
from yt
) d
unpivot
(
val
for col in (rdrgrpid, tzid)
) un
) s
pivot
(
max(val)
for col in (RdrGrpID_1, TZID_1, RdrGrpID_2, TZID_2,
RdrGrpID_3, TZID_3)
) piv
SQL Fiddle with Demoを参照してください。
値の数が不明な場合は、動的 SQL を使用する必要があります。
DECLARE @colsPivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsPivot = STUFF((SELECT ',' + QUOTENAME(c.col + '_'+cast(rn as varchar(10)))
from
(
select row_number() over(partition by partiD, cardnumber
order by rdrgrpid) rn
from yt
) t
cross apply
(
select 'RdrGrpID' col, 1 so union all
select 'TZID', 2
) c
group by col, rn, so
order by rn, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select partid, cardnumber, '+@colsPivot+'
from
(
select partid, cardnumber,
col+''_''+cast(rn as varchar(10)) col,
val
from
(
select partId, cardNumber, RdrGrpID, TZID
, row_number() over(partition by partiD, cardnumber
order by rdrgrpid) rn
from yt
) d
unpivot
(
val
for col in (rdrgrpid, tzid)
) un
) s
pivot
(
max(val)
for col in ('+ @colspivot +')
) p'
exec(@query);
SQL Fiddle with Demoを参照してください。すべてのバージョンで結果が得られます。
| PARTID | CARDNUMBER | RDRGRPID_1 | TZID_1 | RDRGRPID_2 | TZID_2 | RDRGRPID_3 | TZID_3 |
-----------------------------------------------------------------------------------------
| 0 | 412 | 31 | 1 | 34 | 1 | (null) | (null) |
| 0 | 567 | 33 | 5 | 38 | 1 | 71 | 3 |