datetime—两个日期和两个时间之间的sql查询,仅适用于工作日

byqmnocz  于 2021-08-13  发布在  Java
关注(0)|答案(2)|浏览(451)

我正在尝试编写一个查询,它将为我提供在两个特定时间内两个特定日期之间完成的程序数,但仅限于工作日。我有日期和时间的脚本工作,但我不知道如何得到它,所以它只包括工作日。我只想要星期一到星期五的结果,不包括星期六和星期天的结果。
我的问题:

SELECT MONTH(r.LastModifiedDate) AS MONTHpreCOVID, PlacerFld2 AS MODALITY, COUNT(*) AS CountOfReportsDayTimePreCOVID
FROM [order] o

LEFT JOIN report r
ON o.reportID = r.reportID

WHERE r.LastModifiedDate >= '2019-07-01' AND r.lastmodifieddate <= '2020-06-01'
AND CAST(r.lastmodifieddate as TIME) >= '08:00:00' AND CAST(r.lastmodifieddate as TIME) <='16:59:59'
AND reportstatusID = '7'
AND r.creatorAcctID = '139'

GROUP BY MONTH(r.LastModifiedDate), PlacerFld2
ORDER BY MONTH(r.LastModifiedDate) ASC

我尝试在('0','1','2','3','4')中添加类似weekday(r.lastmodifieddate)的内容,但这不起作用。

aelbi1ox

aelbi1ox1#

使用此选项:

AND (((DATEPART(DW, r.lastmodifieddate) - 1 ) + @@DATEFIRST ) % 7) in ('1','2','3','4','5')
``` `(((DATEPART(DW, r.lastmodifieddate) - 1 ) + @@DATEFIRST ) % 7)` 将始终返回一个介于0和6之间的数字,其中每个数字都是:

0 -> Sunday
1 -> Monday
2 -> Tuesday
3 -> Wednesday
4 -> Thursday
5 -> Friday
6 -> Saturday

你可以用这样一个简单的查询来检查它

SELECT (((DATEPART(DW, @DATE_VAR) - 1 ) + @@DATEFIRST ) % 7)

替换 `@DATE_VAR` 有效日期。i、 克 `1900-01-01` 
pftdvrlh

pftdvrlh2#

您可以将一周中的某一天确定为datepart(weekday,dt)。
让你看看

Select Dt, DATEPART(WEEKDAY, dt) as WeekDayNumber, DATEName(WEEKDAY, dt) as WeekDayName
 from
(
Select Getdate() as Dt Union
Select Getdate() + 1 Union
Select Getdate() + 2 Union
Select Getdate() + 3 Union
Select Getdate() + 4 Union
Select Getdate() + 5 Union
Select Getdate() + 6 Union
Select Getdate() + 7 
) Q
Where DATEPART(WEEKDAY, dt) Not In ( 1,7)

所以对你来说,应该是

....
WHERE r.LastModifiedDate >= '2019-07-01' AND r.lastmodifieddate <= '2020-06-01'
AND CAST(r.lastmodifieddate as TIME) >= '08:00:00' AND CAST(r.lastmodifieddate as TIME) <='16:59:59'
AND reportstatusID = '7'
AND r.creatorAcctID = '139'
AND DATEPART(WEEKDAY, r.LastModifiedDate) Not In ( 1,7)

相关问题