即時嘗試從我的表中返回一個矩陣。 我的兩個表如下所示:使用動態SQL
**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
我需要一個表是這樣的: 其中CourseCode和週期會像CourseCode /週期表中的數據,且只能包含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
我GET-錯誤>
Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'pivot'.
謝謝!我已經這樣做了,但是現在又出現了另一個錯誤: Msg 8117,Level 16,State 1,Line 1 對於sum運算符,操作數數據類型nchar無效。 Msg 8156,級別16,狀態1,行1 'pivot_table'多次指定'a3'列。 –