我正在尋找關於重新分解下面顯示的代碼的建議。您會注意到,標識爲「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
你應該包括SQL的意圖是什麼。爲給定的輸入正確輸出會很有用。 –