在SQL中,如何转换位值?

时间:2015-01-08 17:44:53

标签: sql sql-server

以下查询旨在为给定班级中的每个学生创建出勤历史记录。 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)

1 个答案:

答案 0 :(得分:1)

您无法在bitMax运营商中使用数据类型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

SQLFIDDLE DEMO