我正在處理透視問題。我想出了一些代碼,但在編寫代碼時一直沒有成功。請有人給我一些指導,說明我在這裏做錯了什麼?數據透視表代碼,需要一些想法
我有表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:如果有一些特別的東西,你必須做的就是人回答/您的帖子作出迴應,請隨時在你的迴應分享。
謝謝!完善! – user2573624