我有这样的出勤表:
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
请帮助我获得预期的输出.....
答案 0 :(得分:0)
您需要创建一个过程并使用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
答案 1 :(得分:0)
可能是这个作品
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;