如何在MySQL中重写这个“with”查询?
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 :(得分:0)
您需要将current_employees
和appointments_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