당신은 plan_date
의 최대 수를 알 수없는 경우 동적 SQL을 사용해야합니다. pivot()
과 함께 사용하기 위해 Child_Code
으로 분할 된 각 목록의 번호를 지정하려면 row_number()
을 사용해야합니다.
테스트 설정 :
create table t (child_code varchar(6), plan_date datetime);
insert into t values ('000001','20170221'),('000001','20170321');
declare @cols nvarchar(max);
declare @sql nvarchar(max);
select @cols = stuff((
select distinct
',' + quotename('Plan_Date_'
+convert(nvarchar(10),row_number() over (
partition by Child_Code
order by Plan_Date
))
)
from t
for xml path (''), type).value('.','nvarchar(max)')
,1,1,'');
select @sql = '
select Child_Code, ' + @cols + '
from (
select
Child_Code
, Plan_Date
, rn=''Plan_Date_''+convert(nvarchar(10),row_number() over (
partition by Child_Code
order by Plan_Date
))
from t
) as a
pivot (max([Plan_Date]) for [rn] in (' + @cols + ')) p';
select @sql as CodeGenerated;
exec sp_executesql @sql;
rextester 데모 : http://rextester.com/YQCR87525
코드가 생성 :
select Child_Code, [Plan_Date_1],[Plan_Date_2]
from (
select
Child_Code
, Plan_Date
, rn='Plan_Date_'+convert(nvarchar(10),row_number() over (
partition by Child_Code
order by Plan_Date
))
from t
) as a
pivot (max([Plan_Date]) for [rn] in ([Plan_Date_1],[Plan_Date_2])) p
반환
+------------+---------------------+---------------------+
| Child_Code | Plan_Date_1 | Plan_Date_2 |
+------------+---------------------+---------------------+
| 000001 | 21.02.2017 00:00:00 | 21.03.2017 00:00:00 |
+------------+---------------------+---------------------+
점유율 % SQL Server에서 'Pivot'을 사용하여 [행을 열로 변환] 복제본 (http://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql-server) –
일부 추가 더 많은 샘플 데이터를 사용하면 더 까다 롭고 자세한 설명이 가능합니다. (코드 당 항상 두 개의 날짜가있는 경우 그룹 단위로 작업 할 수 있습니다.) – jarlh