2013-08-19 20 views
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 

出把查詢的是像

enter image description here

想我這樣的輸出:

enter image description here

+2

沒有違法,但你嘗試過這樣做並沒有什麼工作?不要期望有人爲你做這項工作。來一個問題 - 期待幫助。訂單 - 付款。 –

回答

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