简体   繁体   English

如何在SQL Server中包括一周中最后一天的小时数

[英]How to include hours for the last day of the week in sql server

I am writing this query: 我在写这个查询:

SELECT 
    DATEADD(wk, DATEDIFF(wk, 0, vr_EmployeeLog.DateTimeStart), 0) period_start,
    DATEADD(wk, DATEDIFF(wk, 0, vr_EmployeeLog.DateTimeStart), 6) period_end 
FROM
    vr_EmployeeLog

I am getting the result: 我得到结果:

period_start   2015-10-12 00:00:00.000
period end     2015-10-18 00:00:00.000

but I got records for period_end date 2015-10-18 01:56:00.000 AM and its not including in the result. 但我获得了period_end日期2015-10-18 01:56:00.000 AM的记录,其结果中未包含该记录。

How can I achieve this? 我该如何实现?

Try using days instead of weeks. 尝试使用几天而不是几周。

SELECT 
    DATEADD(wk,DATEDIFF(wk,0,vr_EmployeeLog.DateTimeStart),0) period_start,
    DATEADD(day,DATEDIFF(day,0,vr_EmployeeLog.DateTimeStart),7) period_end         
FROM vr_EmployeeLog

But to choose data via a "date range" use a combination of greater than or equal to then less then (the next day) 但是要通过“日期范围”选择数据,请使用大于或等于然后小于(第二天)的组合

SELECT *
FROM vr_EmployeeLog
WHERE vr_EmployeeLog.DateTimeStart >= '20151012'
AND vr_EmployeeLog.DateTimeStart < '20151019' --<< "the next day"

Do not be tempted to use "between" for this, always use >= and < 不要试图为此使用“之间”,请始终使用> =和<

the best practice with date and time ranges is to avoid BETWEEN and to always use the form: 日期和时间范围的最佳做法是避免使用BETWEEN,并始终使用以下形式:

WHERE col >= '20120101' AND col < '20120201' This form works with all types and all precisions, regardless of whether the time part is applicable. col> ='20120101'和col <'20120201'此表单适用于所有类型和所有精度,无论时间部分是否适用。

Itzik Ben-Gan 伊齐克·本甘

also

Bad habits to kick : mis-handling date / range queries 不良习惯:错误处理日期/范围查询

I think you should try: 我认为您应该尝试:

SELECT 
    DATEADD(wk,DATEDIFF(wk,0,DateTimeStart),0) period_start,
    DATEADD(day, 6, DATEADD(wk,DATEDIFF(wk,0,DateTimeStart),0)) period_end
FROM vr_EmployeeLog

--ADD 6 days into period_start

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM