You will need to use dynamic sql if the maximum number of plan_date
is unknown. You will need to use row_number()
to number each list partitioned by Child_Code
for use with pivot()
.
test setup:
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 demo: http://rextester.com/YQCR87525
code generated:
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
returns
+------------+---------------------+---------------------+
| Child_Code | Plan_Date_1 | Plan_Date_2 |
+------------+---------------------+---------------------+
| 000001 | 21.02.2017 00:00:00 | 21.03.2017 00:00:00 |
+------------+---------------------+---------------------+