0

我正在寻找有关重构下面显示的代码的建议。您会注意到标识为“DATAPOINT2”和“DATAPOINT3”的代码非常相似并且可以简化。但我正在尝试思考如何优雅地结合“DATAPOINT2”和“DATAPOINT3”。

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
4

1 回答 1

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
于 2013-06-22T02:54:28.770 回答