日期:2014-05-18  浏览次数:20613 次

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

------解决方案--------------------
select
b.*
from
(select distinct(convert(char(10),日期,120))+ ' 08:00:00 ' as 日期 from 表) a,
表 b
where
a.日期> b.日期
and
not exists(select 1 from 表 where 日期 <a.日期 and 日期> b.日期)
------解决方案--------------------
select top 1 * from table_name
where convert(varchar(10), time_column, 112) < convert(varchar(8), getdate(), 112) + '08 '
order by time_column desc

------解决方案--------------------
select top 1 * from table_name
where convert(varchar(13), time_column, 120) < convert(varchar(11), getdate(), 120) + '08 '
order by time_column desc
------解决方案--------------------
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 > A.TestTime And DatePart(Hour, TestTime) < 8)
And DatePart(Hour, TestTime) < 8
GO
Drop Table TEST
--Result
/*
ID TestTime
1 2007-03-29 07:30:00.000
3 2007-03-30 07:00:00.000
5 2007-03-31 07:50:00.000
*/
------解决方案--------------------
select top 1 * from table_name
where convert(varchar(10), time_column, 121) < convert(varchar(7), getdate(), 121) + '-08 '
order by time_column desc
------解决方案--------------------
Create Table TEST(ID Int, TestTime DateTime)
Insert TEST Select 1, '2007-03-19 07:30:00 '
Union All Select 2, '2007-03-19 08:00:00 '
Union All Select 3, '2007-03-20 07:00:00 '
Union All Select 4, '2007-03-21 07:00:00 '
Union All Select 5, '2007-03-21 07:50:00 '
Union All Select 6, '2007-03-22 18:08:00 '
Union All Select 7, '2007-03-23 08:00:00 '
GO
Select * From TEST A
Where Not Exists(Select 1 From TEST
Where (DateDiff(dd, TestTime, A.TestTime) = 0 And TestTime > A.TestTime And DatePart(Hour, TestTime) <= 8)
or
(DateDiff(dd, TestTime, A.TestTime) = 1 And TestTime < A.TestTime And DatePart(Hour, TestTime) > 8)

)
GO
drop table test
go
------解决方案--------------------
if object_id( 'pubs..tb ') is not null
drop table tb
go

create table tb(id int,dt datetime,value int)
insert into tb(id,dt,value) values(1, '2007-03-01 01:00:00 ', 1)
insert into tb(id,dt,value) values(1, '2007-03-01 02:00:00 ', 2)
insert into tb(id,dt,value) values(1, '2007-03-01 03:00:00 ', 3)
insert into tb(id,dt,value) values(1, '2007-03-01 04:00:00 ', 4)
insert into tb(id,dt,value) values(1, '2007-03-01 05:00:00 ', 5)
insert into tb(id,dt,value) values(2, '2007-03-01 06:00:00 ', 6)
insert into tb(id,dt,value) values(2, '2007-03-01 07:00:00 ', 7)
insert into tb(id,dt,value) values(2, '2007-03-01 08:00:00 ', 8)