我需要创建一个SQL Server 2012 SELECT
语句,它将为我提供表格中的上一行。我需要指定当前的日期时间,并让查询返回[TargetDate]
列中存储的最接近的上一个日期时间。
所以在表格中我可能有......
[TargetUnit] [TargetDate]
-----------------------------------
4 2015-12-09 10:15:00
5 2015-12-09 10:30:00
8 2015-12-09 10:45:00
15 2015-12-09 11:00:00
22 2015-12-09 11:15:00
我使用GETDATE()
来查询[TargetDate]
字段。说当前GETDATE()
是2015-12-09 10:37:00
- 然后我需要查询返回[TargetUnit]
5
和[TargetDate]
2015-12-09 10:30:00
的行
答案 0 :(得分:2)
您可以使用top
和order by
来获取所需的记录。
select top 1 [TargetUnit], [TargetDate]
from tbl
where [TargetDate] < GETDATE()
order by [TargetDate] desc
答案 1 :(得分:0)
可以使用datediff和while循环来做,我应该说这是我能想到的最佳选择,如果你正在处理一个可能有FUTURE日期时间的表。直到找到指定日期的最接近的值,未来或过去。
DECLARE @targetdate datetime
DECLARE @getdate datetime = GETDATE()
DECLARE @targetunit int
CREATE TABLE #diffs (targetunit int, targetdate datetime, diffday, diffsec int)
SELECT * INTO #table FROM YOUR_TABLE
WHILE (SELECT COUNT(*) FROM #TABLE) > 0
BEGIN
SELECT TOP 1 @targetunit = targetunit, @targetdate = targetdate FROM #table
DELETE FROM #table WHERE targetunit = @targetunit and targetdate = @targetdate
INSERT INTO #diff
SELECT @targetunit, @targetdate, datediff(day, @targetdate, @getdate), Datediff(second, @targetdate, @getdate)
END
SELECT targetunit, targetdate, MIN(diffday) diffday, MIN(diffsec) diffsec
INTO #mins
FROM #diff
SELECT *
FROM #diff a
JOIN #mins b on a.targetunit = b.targetunit
WHERE a.diffday = b.diffday and a.diffsec = b.diffsec