每个员工需要根据每个月的开始日期获得值的总和

问题描述 投票:0回答:1

栏目:

Emp#,参加日期,小时,

在 SQL 中,我正在寻找一个迭代查询,其中每个员工从开始日期开始,应该获取到当前日期为止应该发生的总小时数。当没有值时,它应该返回或 NULL。 示例:员工 010 开始日期为 15/02/2022;

2022 年 2 月 15 日开始参加日期;每个参加日期都有时间

15/02/2022 --> 6

16/02/2022 --> 8

14/03/2022 --> 8

从 15/03/2022 到 14/04/2022

18/03/2022 --> 4

20/03/2022 --> 8

23/03/2022 --> 6

因此,在 15/02/2022 和 14/03/2022 之间,总小时数为 22;

因此,在 15/03/2022 和 14/04/2022 之间,总小时数为 18 小时; 样本数据:

员工该月的工作时间为15/02/2022至14/03/2022;从开始日期起每个月等等

员工 1 于 2022 年 2 月 15 日开始工作,因此需要开始日期和下个月同一天 1 之间的总工时。

员工 开始日期 结束日期 时间
010 2022年2月15日 2022年3月14日 22
010 2022年3月15日 2022年4月14日 18

提前致谢

sql recursive-query
1个回答
0
投票

开始日期逻辑: 首先检查出勤日期是否小于15日。如果是,则从中减去天数即可得到上个月。然后硬编码第 15 天。如果日期是从 1 到 14,则直接硬编码 15 日 到该月、年。

结束日期逻辑: 如果日期是 1 到 14 日之间,则直接将 硬编码 14 到月、年。如果不是,则首先将日期硬编码为该年月的 15 日,然后添加 20 天以获取下个月、年,然后将日期硬编码为 14 日 下面是查询(我使用了 Hive 数据库和 HQL)。您可以根据您的数据库更改语法或命令: att_date 是出席日期。

select emp_id, start_date, end_date, sum(w_hours) as total_hours from ( select *, case when cast(substring(att_date,1,2) as int)<15 then concat('15',substring(from_unixtime(unix_timestamp(date_sub(from_unixtime(unix_timestamp(att_date,'dd/MM/yyyy'),'yyyy-MM-dd'),cast(substring(att_date,1,2) as int)),'yyyy-MM-dd'),'dd/MM/yyyy'),3)) else concat('15',substring(att_date,3)) end as start_date, case when cast(substring(att_date,1,2) as int)<15 then concat('14',substring(att_date,3)) else concat('14',substring(from_unixtime(unix_timestamp(date_sub(from_unixtime(unix_timestamp(concat('15',substring(att_date,3)),'dd/MM/yyyy'),'yyyy-MM-dd'),-20),'yyyy-MM-dd'),'dd/MM/yyyy'),3)) end as end_date from emp_work_hrs e) calcultd_tbl group by emp_id, start_date, end_date;

© www.soinside.com 2019 - 2024. All rights reserved.