我怎样才能透视此行

时间:2013-04-25 04:47:21

标签: sql sql-server-2008 tsql pivot

我的基本查询

 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 ')'

1 个答案:

答案 0 :(得分:2)

SQL Server不允许PIVOT子句中的子查询。您必须使用动态SQL,或明确列出它们(静态列表)。

e.g。

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