2013-04-25 45 views
0

我的基本查詢我怎麼可以透視這一行

ID   Days  Y Type 
3014 L;M;M;J;V;S;D 15 PDC 
3014 L;M;M;J;V;S;D 16 PDC 
3014 NULL   17 PDC 
3014 NULL   18 PDC 
3014 NULL   19 PDC 
3014 NULL   20 Altern 
3014 NULL   21 Altern 

我想要實現

3014 L;M;M;J;V;S;D L;M;M;J;V;S;D NULL NULL NULL NULL 15 16 17 

我的SQL

select * from (select 
    FS.FieldStudyId, 
    C.Day as Dayss, 
    C.IDCourse, 
    C.Type 
from 
    FieldStudy FS, 
    Course C 
where 
    Fs.FieldStudyId = C.FieldStudyId)d 
pivot 
(
    max(Dayss) 
    for FieldStudyId in (select z.FieldStudyId from FieldStudy z) 
)x; 

但我不工作

Msg 156, Level 15, State 1, Line 14 Incorrect syntax near the keyword 'select'. 
Msg 102, Level 15, State 1, Line 14 Incorrect syntax near ')' 

回答

2

SQL Server不允許PIVOT子句中的子查詢。您將不得不採用動態SQL,或者顯式列出它們(靜態列表)。

例如

declare @sql nvarchar(max); 
select @sql = isnull(@sql + ',', '') + quotename(FieldStudyId) 
from FieldStudy 

set @sql = ' 
select * 
from (
    select 
     FS.FieldStudyId, 
     C.Day as Dayss, 
     C.IDCourse, 
     C.Type 
    from 
     FieldStudy FS, 
     Course C 
    where 
     Fs.FieldStudyId = C.FieldStudyId)d 
pivot 
(
    max(Dayss) 
    for FieldStudyId in (' + @sql + ') 
)x;'; 
exec (@sql); 

雖然這展示瞭如何使用PIVOT列的動態列表,因爲這個問題不明確都不會產生在你的問題的答案。有輕微的變化轉動的IDCourse值改爲:

declare @sql nvarchar(max); 
select @sql = isnull(@sql + ',', '') + quotename(IdCourse) 
from Course; 

--select @sql; 

set @sql = ' 
select * 
from (
    select 
     FS.FieldStudyId, 
     C.Day as Dayss, 
     C.IDCourse 
    from 
     FieldStudy FS, 
     Course C 
    where 
     Fs.FieldStudyId = C.FieldStudyId)d 
pivot 
(
    max(Dayss) 
    for IdCourse in (' + @sql + ') 
)x;'; 
exec (@sql); 

你可以得到類似下面:

| FIELDSTUDYID |   15 |   16 |  17 |  18 |  19 |  20 |  21 | 
--------------------------------------------------------------------------------------------- 
|   3014 | L;M;M;J;V;S;D | L;M;M;J;V;S;D | (null) | (null) | (null) | (null) | (null) | 

但它不會給你在你的問題後15...16...17