如何使用 IF 条件与 SQL 比较日期
Posted
技术标签:
【中文标题】如何使用 IF 条件与 SQL 比较日期【英文标题】:How how use IF condition for comparing date with SQL 【发布时间】:2019-05-21 06:11:58 【问题描述】:我有一个来自考勤机的 MS ACCESS 表,它由 USERID、CHECKTIME 列组成。
通过 MS Access 中的以下 SQL 查询,我设法排序并找到 MIN(日期和时间)作为开始/打卡,MAX(日期和时间)作为每天打卡(日期/工作日期)
SELECT MIN(a.CHECKTIME) as work_start_time, MAX(a.CHECKTIME) as work_end_time, b.CheckDate as work_date, WEEKDAY(b.CheckDate,2) as work_day, a.USERID as user_id
FROM CHECKINOUT a RIGHT JOIN (
SELECT DISTINCT
DateValue(CHECKTIME) as CheckDate,
USERID FROM CHECKINOUT
WHERE ( MONTH(CHECKTIME) = 4 )
AND YEAR(CHECKTIME) = 2019 AND USERID =50
)
b on a.USERID = b.USERID
and DateValue(a.CHECKTIME) = b.CheckDate GROUP BY b.checkDate, a.USERID
查询结果:
Work_start_Time | work_end_time | Work_date | Work_day |User_ID
1/04/2019 8:30:19 AM | 1/04/2019 8:30:19 AM | 1/04/2019| 1 |50
2/04/2019 12:16:38 AM | 2/04/2019 9:40:52 AM | 2/04/2019| 2 |50
3/04/2019 1:25:29 AM | 3/04/2019 1:25:29 AM | 3/04/2019| 3 |50
4/04/2019 7:09:26 AM | 4/04/2019 9:10:37 PM | 4/04/2019| 4 |50
我想做的是,如果第二天 (CHECKTIME +1) work_start_time 小于 5AM,那么第二天的 MIN(CHECKTIME) 就变成了 Work_end_time。
SELECT MIN(a.CHECKTIME) as work_start_time,
IF (MIN(a.CHECKTIME+1) < 5:00:00 AM )
MIN(a.CHECKTIME+1) as work_end_time,
ELSE
MAX(a.CHECKTIME) as work_end_time,
b.CheckDate as work_date, WEEKDAY(b.CheckDate,2) as work_day, a.USERID as user_id
FROM CHECKINOUT a RIGHT JOIN (
SELECT DISTINCT
DateValue(CHECKTIME) as CheckDate,
USERID FROM CHECKINOUT
WHERE ( MONTH(CHECKTIME) = 4 )
AND YEAR(CHECKTIME) = 2019 AND USERID =50
)
b on a.USERID = b.USERID
and DateValue(a.CHECKTIME) = b.CheckDate GROUP BY b.checkDate, a.USERID
查询结果:
Work_start_Time | work_end_time | Work_date | Work_day |User_ID
1/04/2019 8:30:19 AM | 2/04/2019 12:16:38AM | 1/04/2019| 1 |50
2/04/2019 9:40:52 AM | 3/04/2019 1:25:29 AM | 2/04/2019| 2 |50
3/04/2019 1:25:29 AM | 3/04/2019 1:25:29 AM | 3/04/2019| 3 |50
4/04/2019 7:09:26 AM | 4/04/2019 9:10:37 PM | 4/04/2019| 4 |50
【问题讨论】:
【参考方案1】:尝试使用IIF:
IIF(TimeValue(MIN(a.CHECKTIME)) < #05:00:00#), MIN(a.CHECKTIME+1), MAX(a.CHECKTIME)) as work_end_time,
【讨论】:
感谢 Gustav,IIF 声明有效,但总是错误的。我假设 是的。必须排除日期部分。请查看编辑后的答案。 谢谢古斯塔夫,不知何故仍未给出我预期的逻辑。但它给了我一个开始和玩耍的点。非常感谢。真棒 您可以提供一些示例数据。但如果您觉得是,请标记为已回答。以上是关于如何使用 IF 条件与 SQL 比较日期的主要内容,如果未能解决你的问题,请参考以下文章
如何在 sql server 2008 中将日期与 GETDATE() 进行比较
如何在spark sql lag函数中添加if或case条件
如何在 SQL Server 2008 的 where 子句中仅比较日期并忽略时间