0

我有以下查询:

SELECT  
        at.empId
    ,   e.name
    ,   ao.name
FROM Attendance at
LEFT OUTER JOIN AttendanceOption ao ON at.Attendance = ao.id
LEFT OUTER JOIN Employee e ON at.EmpId = e.id
WHERE at.AttendanceDate = '08/30/2013'
GROUP BY
        ao.name
    ,   at.EmpId
    ,   e.name

查询的输出就像

在此处输入图像描述

我想要这样的输出:

在此处输入图像描述

4

1 回答 1

0

试试这个——

询问 -

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
于 2013-08-19T11:45:12.153 回答