我正在创建一个ASP.NET应用程序(C#),我差不多完成了,但是我有以下问题。
方案
在我的MSSQL表中,我有一个日期时间值,即 2015-05-06 13:38:17.000 我需要知道这是否超过6个小时但是我需要考虑到事实上,我们只在周一至周五的8:30-18:00工作。
我目前正在研究一个项目是否超过4个小时(不考虑工作时间),使用以下查询:
SELECT COUNT(*) FROM Table WHERE [DateSubmitted] < DATEADD(HOUR,-4,GETDATE())
我已经了解了如何计算工作时间:Calculate business hours between two dates但我不知道如何将其应用于我想要做的事情。
任何帮助将不胜感激 - 谢谢。
答案 0 :(得分:1)
只需在营业时间内获取最长日期,然后使用该参数进行查询
DECLARE @EndDate DATETIME, @StartBusinessDay DATETIME, @YesterdayEndBusinessDay DATETIME,@Interval DECIMAL(10,2)
SET @Interval=4*3600*-1
--set start period of business hour
--you can change hard coded date to variable one
SELECT @StartBusinessDay=CAST('2015-06-17 08:00:00' AS datetime),
@YesterdayEndBusinessDay =CAST('2015-06-16 17:00:00' AS datetime)
--get maximal date with basic calculation
SELECT @EndDate=DATEADD(ss,@Interval, GETDATE())
--if max date is not within business hour, do this
IF(@EndDate<@StartBusinessDay)
BEGIN
DECLARE @Difference DECIMAL(4,2)
--get the difference between result of basic calculation and start business hour
SELECT @Difference=DATEDIFF(ss, @EndDate, @StartBusinessDay)
--subtract it with initial interval
SET @Difference=@Interval-@Difference;
--get the new max date within business hour
SELECT @EndDate=DATEADD(ss,@Difference,@YesterdayEndBusinessDay)
SELECT @EndDate
END
--query with max date within business hour
SELECT COUNT(1) FROM Table
WHERE [DateSubmitted] < @EndDate