SQL Server中如何将列转换为行
我有一张这样的考勤表:SQL Server中如何将列转换为行,sql,sql-server,Sql,Sql Server,我有一张这样的考勤表: Student_id attendance_date status ----------- ---------------- --------- 1 1/8/2014 Present 2 1/8/2015 Absent 1 2/8/2014 Present 2 2/8/2015 Present
Student_id attendance_date status
----------- ---------------- ---------
1 1/8/2014 Present
2 1/8/2015 Absent
1 2/8/2014 Present
2 2/8/2015 Present
1 3/8/2014 Present
2 3/8/2015 Present
预期产出如下:
Student_ id 1/8/2014 2/8/2014 3/8/2014
------------- --------- --------- ----------
1 present present present
2 absent present present
请帮助我获得预期的输出…您需要创建一个过程,并使用Dynamic Pivot进行如下操作
DECLARE @dates NVARCHAR(MAX)
DECLARE @query AS NVARCHAR(MAX)
--Get all the dates to pivot
SELECT @dates = ISNULL(@dates + ',','')
+ QUOTENAME(attendance_date)
FROM (SELECT DISTINCT attendance_date FROM attendance) AS attendance
--Construct the dynamic pivot query
SET @query =
N'SELECT status, ' + @dates + '
FROM attendance
PIVOT(MAX(status)
FOR dates IN (' + @dates + ')) AS pivotTable'
-- excecute the dynamic query
EXEC sp_executesql @query
这可能有用吗
SELECT t.[user_id], t.[attendance_date],t.[status]
FROM Attendance t
PIVOT ( MIN(status)
FOR attendance_date IN ([1/8/2014],[2/8/2014],[3/8/2014]) ) pvt;
您正在寻找数据透视图。您还需要格式化日期字符串,尤其是。。。这里将日期或日期时间值与字符串进行比较。并在设置@dates和@query值的查询中包含一个日期范围筛选器。我收到以下错误:-“PIVOT”附近的语法不正确。您可能需要将当前数据库的兼容性级别设置为更高的值才能启用此功能。有关ALTER DATABASE的“设置兼容性”级别选项,请参阅帮助。