如何查询每天8点前的最后一条记录?

电表读数问题,电表每天按固定时间间隔读取数据,报表要求提取出每天8点前的最后一条记录做为前一天的读数,SQL语句怎么写?

Create Table TEST(ID Int, TestTime DateTime)
Insert TEST Select 1, '2007-03-29 07:30:00'
Union All Select 2, '2007-03-29 08:00:00'
Union All Select 3, '2007-03-30 07:00:00'
Union All Select 4, '2007-03-31 07:00:00'
Union All Select 5, '2007-03-31 07:50:00'
GO
Select * From TEST A
Where Not Exists(Select 1 From TEST Where DateDiff(dd, TestTime, A.TestTime) = 0 And TestTime &gt; A.TestTime And DatePart(Hour, TestTime) < 8)
And DatePart(Hour, TestTime) < 8
GO
Drop Table TEST


--Result

ID     Test           Time
1     2007-03-29     07:30:00.000
3     2007-03-30     07:00:00.000
5     2007-03-31     07:50:00.000

你可能感兴趣的:(sql,Go)