使用动态 Sql

Using Dynamic Sql

我正在尝试 return 来自我 table 的矩阵。 我的两个 table 看起来像这样:

**Employe_Course_Instance**
PersonNumber Year Period CourseCode Hour
111          2015   3     a1         10
222          2016   4     a2         4
333          2018   2     a3         8
444          2015   1     a4         5

**Employe**
PersonNumber FirstName LastName Salary Type
    111          A        LA     100   teacher 
    222          B        LB     120   teacher 
    333          C        LC     150   teacher 
    444          D        LD     120   teacher 

我需要 table 如下所示: 其中 CourseCode 和 period 将是 table 中的数据,如 CourseCode/Period 并且只能包含 4 个周期。 CourseCode/Period.

中的行显示工资
FirstName LastName a1/3 a2/4 a3/2 a4/1 Hours
   A         LA    100                  10
   B         LB         120             4
   C         LC              150        8
   D         LD                   120   5

这就是我尝试这样做的方式->

declare @ColumnNames nvarchar(max) 
declare @SQL nvarchar(max)

set @SQL = ''
set @ColumnNames = ''
select @ColumnNames = @ColumnNames + quotename (coursecode) + ','
from bemaning

set @ColumnNames = left (@ColumnNames, len (@ColumnNames) - 1)

print @ColumnNames

set @SQL = 
'select * from
(select 
employe.firsname, employe.lastname, 
Employe_Course_Instance.coursecode  + '' / '' + CAST(Employe_Course_Instance.period as varchar (50)) as CourseCode_Period,
Employe_Course_Instance.year, Employe_Course_Instance.hours
from
employe inner join Employe_Course_Instance on employe.personnumber = Employe_Course_Instance.personnumber) 


pivot(
    sum(hour)
    for CourseCode_Period in (' + @ColumnNames +')

) as pivot_table'

--print @SQL
execute sp_executesql @SQL

我得到的错误->

Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'pivot'.

是的,那是因为您的内联视图缺少 table alias。应该是

on employe.personnumber = Employe_Course_Instance.personnumber) XXX  
                                                                ^... Here  
pivot(
sum(hour)
for CourseCode_Period in (' + @ColumnNames +')
.....

您需要添加一个 alias

AS <alias for the source query>

FROM 语句之后。于是有了

select * from
(select 
 employe.firsname, employe.lastname, 
 Employe_Course_Instance.coursecode  + '' / '' +  
 CAST(Employe_Course_Instance.period as varchar (50)) as CourseCode_Period,
 Employe_Course_Instance.year, Employe_Course_Instance.hours
 from
employe inner join Employe_Course_Instance on employe.personnumber =   
Employe_Course_Instance.personnumber) AS pvtTable

pivot(

PIVOT documentation