gpt4 book ai didi

sql - 查找唯一的天数

转载 作者:行者123 更新时间:2023-12-03 15:01:21 26 4
gpt4 key购买 nike

我希望编写一个 SQL 查询来从表 times 中查找每个员工的唯一工作日数。 .

*---------------------------------------*
|emp_id task_id start_day end_day |
*---------------------------------------*
| 1 1 'monday' 'wednesday' |
| 1 2 'monday' 'tuesday' |
| 1 3 'friday' 'friday' |
| 2 1 'monday' 'friday' |
| 2 1 'tuesday' 'wednesday' |
*---------------------------------------*

预期输出:
*-------------------*
|emp_id no_of_days |
*-------------------*
| 1 4 |
| 2 5 |
*-------------------*

我写了查询 sqlfiddle这给了我 expected输出但出于好奇,是否有更好的方法来编写此查询?我可以使用日历或理货表吗?
with days_num as  
(
select
*,
case
when start_day = 'monday' then 1
when start_day = 'tuesday' then 2
when start_day = 'wednesday' then 3
when start_day = 'thursday' then 4
when start_day = 'friday' then 5
end as start_day_num,

case
when end_day = 'monday' then 1
when end_day = 'tuesday' then 2
when end_day = 'wednesday' then 3
when end_day = 'thursday' then 4
when end_day = 'friday' then 5
end as end_day_num

from times
),
day_diff as
(
select
emp_id,
case
when
(end_day_num - start_day_num) = 0
then
1
else
(end_day_num - start_day_num)
end as total_diff
from days_num
)

select emp_id,
sum(total_diff) as uniq_working_days
from day_diff
group by
emp_id

任何建议都会很棒。

最佳答案

您基本上需要找到每个emp_id 工作天数的交集。在每个 task用一周中的所有天数,然后计算不同的天数:

with days_num as (
SELECT *
FROM (
VALUES ('monday', 1), ('tuesday', 2), ('wednesday', 3), ('thursday', 4), ('friday', 5)
) AS d (day, day_no)
),
emp_day_nums as (
select emp_id, d1.day_no AS start_day_no, d2.day_no AS end_day_no
from times t
join days_num d1 on d1.day = t.start_day
join days_num d2 on d2.day = t.end_day
)
select emp_id, count(distinct d.day_no) AS distinct_days
from emp_day_nums e
join days_num d on d.day_no between e.start_day_no and e.end_day_no
group by emp_id

输出:
emp_id  distinct_days
1 4
2 5

Demo on SQLFiddle

关于sql - 查找唯一的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60881439/

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