2013-06-22 135 views
0

我正在尋找關於重新分解下面顯示的代碼的建議。您會注意到,標識爲「DATAPOINT2」和「DATAPOINT3」的代碼與簡化非常相似和成熟。但是我正在試圖想想如何優雅地結合'DATAPOINT2'和'DATAPOINT3'。重構SQL代碼

CREATE TABLE Employee (EmployeeId INTEGER, BonusPaidOn DATE, Status VARCHAR(50)); 

INSERT INTO Employee VALUES (1, '01-JAN-2013', 'Paid in Full'); 
INSERT INTO Employee VALUES (2, '01-FEB-2013', 'Paid in Full'); 
INSERT INTO Employee VALUES (2, '01-MAR-2013', 'Partial Payment'); 
INSERT INTO Employee VALUES (2, '01-APR-2013', 'Partial Payment'); 
INSERT INTO Employee VALUES (3, '01-APR-2013', 'Refused'); 
COMMIT; 

WITH 
DATAPOINT1 AS 
    (SELECT DISTINCT 
     EmployeeId 
    FROM 
     Employee 
) 
,DATAPOINT2 AS 
    (SELECT 
     EmployeeId 
     ,Status 
     ,MAX(BonusPaidOn) AS BonusPaidOn 
    FROM 
     Employee 
    WHERE 
    Status IN ('Paid in Full','Partial Payment', 'Refused') 
    GROUP BY 
    EmployeeId, Status 
) 
,DATAPOINT3 AS 
    (SELECT 
     EmployeeId 
     ,MAX(BonusPaidOn) AS BonusPaidOn 
    FROM 
     DATAPOINT2 temp 
    WHERE 
     Status IN ('Paid in Full','Partial Payment') 
    GROUP BY 
     EmployeeId 
) 
SELECT 
    A.EmployeeId 
    ,B.BonusPaidOn AS LastBonusPaidInFullOn 
    ,C.BonusPaidOn AS LastBonusPaidOn 
    ,D.BonusPaidOn AS LastBonusRefusedOn 
FROM 
    DATAPOINT1 A 
LEFT OUTER JOIN DATAPOINT2 B ON A.EmployeeId = B.EmployeeId AND B.Status = 'Paid in Full' 
LEFT OUTER JOIN DATAPOINT3 C ON A.EmployeeId = C.EmployeeId 
LEFT OUTER JOIN DATAPOINT2 D ON A.EmployeeId = D.EmployeeId AND D.Status = 'Refused'; 

請求爲預期的結果作出:

EmployeeId LastBonusPaidInFullOn LastBonusPaidOn LastBonusRefusedOn 
---------- --------------------- --------------- ------------------ 
     3           01-APR-13 
     1 01-JAN-13    01-JAN-13 
     2 01-FEB-13    01-APR-13 
+0

你應該包括SQL的意圖是什麼。爲給定的輸入正確輸出會很有用。 –

回答

1

查詢似乎很複雜。我認爲以下是你想要的 - 爲每個狀態類型創建最後一個日期:

SELECT EmployeeId, 
     max(case when Status IN ('Paid in Full') then BonusPaidOn 
      end) as LastBonusPaidInFullOn 
     max(case when Status IN ('Partial Payment') then BonusPaidOn 
      end) as LastBonusPaidOn 
     max(case when Status IN ('Refused') then BonusPaidOn 
      end) as BonusPaidPartialRefused 
FROM Employee 
WHERE Status IN ('Paid in Full', 'Partial Payment', 'Refused') 
GROUP BY EmployeeId 
+0

我不太清楚你如何評價優雅,但我確實喜歡Gordon的SQL。我希望他不介意我調整了一下,以獲得我期待的結果。 – user1356996

+0

@ user1356996。 。 。變化很好。很高興我能夠提供幫助。 –