我正在研究一个枢轴问题。我想出了一些代码,但未能成功编写代码。请有人能给我一些关于我在这里做错了什么的指导吗?
我有表 1,它是在下面的代码中创建的:
create table T1 (
[name] varchar(30)
,[size] int
,[DT] date)
insert into T1 values ( 'x1', 14, '01/03/2013' );
insert into T1 values ( 'x1', 134, '01/04/2013' );
insert into T1 values ( 'x1', 199, '01/05/2013' );
insert into T1 values ( 'x1', 284, '01/06/2013' );
insert into T1 values ( 'x2', 212, '01/03/2013' );
insert into T1 values ( 'x2', 369, '01/04/2013' );
insert into T1 values ( 'x2', 439, '01/05/2013' );
insert into T1 values ( 'x2', 555, '01/06/2013' );
我需要将表格转换为这种格式:
01/03/13 01/04/2013 01/05/2013 01/16/2013
X1 14 134 199 284
X2 212 369 439 555
这是我一直在处理的代码,但未能成功地将其用于上述输出?对我有什么想法或指示吗?提前致谢...
declare @DateList as varchar(max)
declare @dynamic_PQ as varchar(max)
select @DateList =
stuff( (
select DISTINCT
', '+ Quotename(CONVERT(VARCHAR(10),DT,110))
from
( select dt from t1 ) t
for xml path ('')
),1,1,'')
select @DateList
set @dynamic_PQ = 'select [GuestID], ' + @DateList +
' from
(
Select [name],
size,
STUFF((SELECT distinct '', '' + convert(a2.size as varch(10))
from t1 a2
where src.name = a2.name
and src.dt = a2.dt
FOR XML PATH(''''), TYPE
).value(''.'', ''NVARCHAR(MAX)'')
,1,1,'''') answer
from
(
select name,
dt ,
size
from t1
) src
) as S
PIVOT
(
MAX([size])
for Question IN (' + @DateList + ')
) as P
Exec(@dynamic_PQ)
PS:如果您需要做一些特别的事情来让任何人回答/回复您的帖子,请随时在您的回复中分享。