试试这个——
询问 -
DECLARE @temp TABLE
(
ID INT IDENTITY(1,1) PRIMARY KEY
, AttendanceName VARCHAR(20)
, AttendanceOptionName VARCHAR(20)
)
INSERT INTO @temp (AttendanceName, AttendanceOptionName)
VALUES
('a1', 'Absent'),('a2', 'Absent'),('a3', 'Absent'),
('b1', 'Half Day'),('b2', 'Half Day'),
('c1', 'Present'),('c2', 'Present'),('c3', 'Present'),('c4', 'Present'),
('d1', 'Without Notification'),('d2', 'Without Notification')
SELECT [Absent], [Half Day], [Present], [Without Notification]
FROM (
SELECT
AttendanceName
, AttendanceOptionName
, rn = ROW_NUMBER() OVER (PARTITION BY AttendanceOptionName ORDER BY 1/0)
FROM @temp
) t
PIVOT
(
MAX(AttendanceName)
FOR AttendanceOptionName IN ([Absent], [Half Day], [Present], [Without Notification])
) p
输出 -
Absent Half Day Present Without Notification
-------- --------- --------- --------------------
a1 b1 c1 d1
a2 b2 c2 d2
a3 NULL c3 NULL
NULL NULL c4 NULL
更新 #2 -
SELECT [Absent]
, [Half Day]
, [Present]
, [Without Notification]
FROM
(
SELECT AttendanceName = e.name
, AttendanceOptionName = ao.name
, rn = ROW_NUMBER() OVER (PARTITION BY ao.name ORDER BY 1/0)
FROM dbo.Attendance at
JOIN dbo.AttendanceOption ao ON at.Attendance = ao.id
JOIN dbo.Employee e ON at.EmpId = e.id
WHERE at.AttendanceDate = '20130830'
GROUP BY
ao.name
, at.EmpId
, e.name
, e.id
) t
PIVOT (
MAX(AttendanceName)
FOR AttendanceOptionName IN ([Absent], [Half Day], [Present], [Without Notification])
) p