gpt4 book ai didi

mysql - 将 'with' 查询转换为 mysql 查询

转载 作者:行者123 更新时间:2023-11-29 21:08:17 25 4
gpt4 key购买 nike

如何在 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

最佳答案

您需要将 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

关于mysql - 将 'with' 查询转换为 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36620234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com