如何在SQL Server中检索最近几个小时的记录

时间:2011-09-23 07:30:36

标签: asp.net sql vb.net sql-server-2008

他们有一个asp.net(vb)Web应用程序来存储加班(OT)记录。

在SQL服务器中,OT表喜欢这样,例如:

ot_key | From Time        | To Time          | total_min
12     | 2011-09-22 10:00 | 2011-09-22 13:00 | 180
13     | 2011-09-24 14:00 | 2011-09-24 15:00 | 60
14     | 2011-09-23 12:00 | 2011-09-23 14:30 | 150
15     | 2011-09-24 18:00 | 2011-09-24 19:30 | 90

由于用户将输入以前的日期OT记录,因此db中的记录将不会按顺序排列。记录#14的日期在记录#13之前。

如果用户想知道过去2小时内哪些OT记录,系统应检索记录#15 (90分钟)& #13 (30分钟),因为它们涵盖最后2个小时。

如何编写SQL语句来检索记录?感谢

3 个答案:

答案 0 :(得分:1)

如果我理解正确的话,你需要做的就是这个(但是你提出问题的方式很奇怪,所以我不确定你在寻找什么。

 select * from OT where total_min <=
 [number of hours expressed in minutes]

答案 1 :(得分:1)

CREATE TABLE OT (
    [ot_key] INT,
    [From Time] DATETIME,
    [To Time] DATETIME,
    [total_min] INT
)

INSERT  OT
VALUES  (12,'2011-09-22 10:00', '2011-09-22 13:00', 180),
        (13, '2011-09-24 14:00', '2011-09-24 15:00', 60),
        (14, '2011-09-23 12:00', '2011-09-23 14:30', 150),
        (15, '2011-09-24 18:00', '2011-09-24 19:30', 90)

查询:

DECLARE @CoverTime INT = 120

;WITH cteOTRN AS (
    SELECT ROW_NUMBER() OVER (ORDER BY [To Time] DESC) AS [ROW_NUMBER], *
    FROM OT
)
, cteOTRT AS (
    SELECT *
    FROM cteOTRN ot
    CROSS APPLY (
        SELECT  SUM([total_min]) AS [RunningTotal]
        FROM cteOTRN
        WHERE [ROW_NUMBER] <= ot.[ROW_NUMBER]
    ) rt
)
SELECT *, [total_min] AS [CoverTime]
FROM cteOTRT ot
WHERE [RunningTotal] <= @CoverTime
UNION 
SELECT TOP 1 *, [RunningTotal] - @CoverTime
FROM cteOTRT ot
WHERE NOT ([RunningTotal] <= @CoverTime)
AND NOT EXISTS (
    SELECT *
    FROM cteOTRT ot
    WHERE [RunningTotal] = @CoverTime
)
ORDER BY [To Time] DESC

另见Calculate a Running Total in SQL Server

答案 2 :(得分:0)

做一个

select * from OT where datediff(hour,ToTime,getdate()) < 2

将为您提供当前时间与全天时间之差小于2小时的帖子。