2016-04-14 178 views
0

如何在MySQL中重寫「with」查詢?將'with'查詢轉換爲mysql查詢

WITH current_employees AS (
     SELECT DISTINCT emp_id 
     FROM appointment 
     WHERE end_date IS NULL 
    ), 
    appointments_2015 AS (
     SELECT a.emp_id, salary, 
      CASE WHEN start_date < ’2015-01-01’ THEN ’2015-01-01’ ELSE start_date END AS start_date, 
      CASE WHEN end_date < ’2016-01-01’ THEN end_date ELSE ’2015-12-31’ END AS end_date 
     FROM appointment a 
      JOIN current_employees ce ON a.emp_id = ce.emp_id 
     WHERE start_date < ’2016-01-01’ AND (end_date >= ’2015-01-01’ OR end_date IS NULL) 
    ) 
    SELECT 
     emp_id, 
     SUM(salary * (DATEDIFF(end_date, start_date) + 1)/365) AS total 
    FROM appointments_2015 
    GROUP BY emp_id 

回答

0

你需要用自己的定義,以取代current_employeesappointments_2015用法:

SELECT 
    emp_id, 
    SUM(salary * (DATEDIFF(end_date, start_date) + 1)/365) AS total 
FROM (
    -- replacement code for appointments_2015 
    SELECT a.emp_id, salary, 
     CASE WHEN start_date < ’2015-01-01’ THEN ’2015-01-01’ ELSE start_date END AS start_date, 
     CASE WHEN end_date < ’2016-01-01’ THEN end_date ELSE ’2015-12-31’ END AS end_date 
    FROM appointment a 
     JOIN ( 
      -- replacement code for current_employees 
      SELECT DISTINCT emp_id 
      FROM appointment 
      WHERE end_date IS NULL 
     ) ce ON a.emp_id = ce.emp_id 
    WHERE start_date < ’2016-01-01’ AND (end_date >= ’2015-01-01’ OR end_date IS NULL) 
) appointments_2015 
GROUP BY emp_id