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

1 回答 1

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问题的尾随。

于 2013-04-25T04:48:41.170 回答