读书人

sql日期查询有关问题求大侠!

发布时间: 2013-07-09 09:50:48 作者: rapoo

sql日期查询问题,求大侠!!!
id date value
200112013-6-24 18:00:0043
200112013-6-24 19:00:0040
200112013-6-24 20:00:0029
200112013-6-24 21:00:0022
200112013-6-24 22:00:0017
200112013-6-24 23:00:0014
200112013-6-25 0:00:006
200112013-6-25 1:00:004
200112013-6-25 2:00:005
200112013-6-25 3:00:004
200112013-6-25 4:00:003
200112013-6-25 5:00:004
200112013-6-25 6:00:008
200112013-6-25 7:00:00396
200112013-6-25 8:00:00701
类似上述数据,一年每天每个时刻都有,如何筛选出(例如:2013-06-25 3:00:00以前 对应每周这个点的数据如2013-06-18 3:00:00,2013-06-11 3:00:00,2013-06-14 3:00:00)同理还有月的!!!
[解决办法]




if object_id('Tempdb..#a') is not null drop table #a
--建临时表
create table #a(
ID int identity(1,1) not null,
pdate datetime null
)
--建示例数据
declare @i int
declare @n int
declare @date datetime
declare @time nvarchar(9)
set @i=1
set @n=1000
set @date='2013-06-25 1:0:0'
set @time=' 03:00:00'
while @i<=@n
begin
insert into #a select dateadd(hh,-1*@i,@date)
set @i=@i+1
end
--查询
;with cte as(
select *,datediff(dd,pdate,@date) days,cast(left(pdate,10)+@time as datetime) theTime from #a
)
select * from cte where days %7=0 and datediff(hh,pdate,theTime)=0

---------------------------
-----查询结果
ID pdate days theTime
----------- ----------------------- ----------- -----------------------
166 2013-06-18 03:00:00.000 7 2013-06-18 03:00:00.000


334 2013-06-11 03:00:00.000 14 2013-06-11 03:00:00.000
502 2013-06-04 03:00:00.000 21 2013-06-04 03:00:00.000
670 2013-05-28 03:00:00.000 28 2013-05-28 03:00:00.000
838 2013-05-21 03:00:00.000 35 2013-05-21 03:00:00.000

(5 行受影响)

读书人网 >SQL Server

热点推荐