2014-05-06 59 views
1

我一直在一個查詢給我的員工在第一和第二次審查日期和審查的結果,一排第二個最低。下面的查詢以兩行(第一行和第二行數)的形式給我提供了這些信息。不過,我需要數據出現在一行中。下面是該查詢我現在有:MSSQL - 最低,使用ROW_NUMBER

SELECT EmployeeID,ReviewDate, ReviewResults FROM 
    (
    SELECT EmployeeID, ReviewDate, ReviewResults, MAX(case when RowNumber = 1 then ReviewDate end) as Lowest FROM 
     (
     Select EmployeeID, a.ReviewDate, isnull(at.ReviewResults,'Not Completed') as ReviewResults, 
     ROW_NUMBER() OVER (PARTITION BY EmployeeID Order By ReviewDate) as RowNumber 
     FROM Employee p 
     LEFT JOIN Administration a on p.EmployeeID = a.ManagerID 
     LEFT JOIN AdminText at on a.ReviewID = at.ReviewID 
     GROUP BY p.EmployeeID, a.ReviewDate, at.ReviewResults 
     ) as sub_inner 
    WHERE ReviewDate>=ISNULL(NULL,'1/1/1900') 
     And ReviewDate<dateadd(day,1,ISNULL(NULL,'1/1/3000')) 
     AND RowNumber Between 1 and 2 
     GROUP BY EmployeeID, ReviewDate, ReviewResults 
    ) as sub_outer 
    GROUP BY EmployeeID, ReviewDate, ReviewResults 

結果是這樣的:

ID  Review Date     ReviewResults 
----  -----------------------  ------------- 
1   2001-07-05 07:45:00.000   No Change 
1   2001-07-28 10:00:00.000   Raise 
2   2001-07-23 10:00:00.000   Promotion 
2   2001-07-28 12:45:00.000   No Change 

我想的是:

ID  Review Date1 Review Date2 ReviewResults1 ReviewResults2 
----  ------------- ------------- ------------- -------------- 
1   2001-07-05  2001-07-28  No Change  Raise 
2   2001-07-23  2001-07-28  Promotion  No Change 

不知道如何實現這一結果?提前致謝。

+1

你能表現出預期的輸出在第二排?你的查詢選擇'ManagerID'。也添加該列。 –

+0

編輯表明。我將Manager ID取出,結果集來自查詢的較新運行,對此抱歉。謝謝。 – dcreight

回答

2

測試數據

DECLARE @TABLE TABLE (ID INT, [Review Date] DATETIME, ReviewResults VARCHAR(100)) 
INSERT INTO @TABLE VALUES 
(1,   '2001-07-05 07:45:00.000',   'No Change'), 
(1,   '2001-07-28 10:00:00.000',   'Raise'), 
(2,   '2001-07-23 10:00:00.000',   'Promotion'), 
(2,   '2001-07-28 12:45:00.000',   'No Change') 

查詢

;WITH CTE 
AS (
    -- You would use your above query here 
    SELECT ID, [Review Date], ReviewResults 
      , ROW_NUMBER() OVER (PARTITION BY ID ORDER BY [Review Date]) rn 
    FROM @TABLE 
    ) 
SELECT C1.ID 
     ,C1.[Review Date] AS [Review Date 1] 
     ,C2.[Review Date] AS [Review Date 2] 
     ,C1.ReviewResults AS [ReviewResults 1] 
     ,C2.ReviewResults AS [ReviewResults 2]  
FROM CTE C1 INNER JOIN CTE C2 
ON C1.ID = C2.ID AND C1.rn +1 = C2.rn 

結果集

╔════╦═════════════════════════╦═════════════════════════╦═════════════════╦═════════════════╗ 
║ ID ║  Review Date 1  ║  Review Date 2  ║ ReviewResults 1 ║ ReviewResults 2 ║ 
╠════╬═════════════════════════╬═════════════════════════╬═════════════════╬═════════════════╣ 
║ 1 ║ 2001-07-05 07:45:00.000 ║ 2001-07-28 10:00:00.000 ║ No Change  ║ Raise   ║ 
║ 2 ║ 2001-07-23 10:00:00.000 ║ 2001-07-28 12:45:00.000 ║ Promotion  ║ No Change  ║ 
╚════╩═════════════════════════╩═════════════════════════╩═════════════════╩═════════════════╝ 
+0

這工作完美。謝謝! – dcreight