如何将我的查询转换为数据透视查询

时间:2013-08-19 11:30:39

标签: sql-server tsql pivot

我有以下查询:

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

查询的输出就像

enter image description here

我想输出如下:

enter image description here

1 个答案:

答案 0 :(得分: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