以下查询旨在为给定班级中的每个学生创建出勤历史记录。 Pupil表包含ID,名称和学术详细信息,而Register表只有四列:ID,StudentID,Time(Datetime)和Present(bit)。它本身工作正常,并将位值转换为整数,所以我得到:
Jim Monday 1
Jim Tuesday 0
Sally Monday 1
Sally Tuesday 1
但是当它使用下面的代码转动时,每个瞳孔的所有值都显示为NULL:
Name Monday Tuesday
Jim Null Null
Sally Null Null
我想要的时候:
Name Monday Tuesday
Jim 1 0
Sally 1 1
也许我已经盯着它看了太久。我真的很感激任何帮助。谢谢!
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
select @cols = STUFF( (SELECT ',' + QUOTENAME(Register.Time)
FROM Register INNER JOIN Pupil on Register.StudentID = Pupil.StudentID
WHERE Pupil.GroupDesignation = 'ClassDesignationGoesHere'
GROUP BY Register.Time ORDER BY Register.Time ASC
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
set @query = 'SELECT FName, SName, ' + @cols + ' FROM
(
SELECT Pupil.FName, Pupil.SName, CAST(Present AS TINYINT) AS INTPresent, Register.Time
FROM Register INNER JOIN Pupil ON Register.StudentID = Pupil.StudentID
WHERE Pupil.GroupDesignation = ''ClassDesignationGoesHere''
) x
PIVOT (MAX(INTPresent) for Time in (' + @cols + ') ) p ' execute(@query)
答案 0 :(得分:1)
您无法在bit
或Max
运营商中使用数据类型min
。
您需要将其转换为Int
来源查询
Pivot
SELECT *
FROM (SELECT NAME,
dates,
CONVERT(INT, flag) flag
FROM result)a
PIVOT (Max(flag)
FOR dates IN([Monday],
[Tuesday])) piv
希望您可以将其转换为Dynamic pivot