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

SQL 取时间断问题,求高高高手介入! 在线等待。。急
情况说明: ddd为 datetime类型
表名:T

ddd A B C

2012-05-26 14:15:45 23 78 98
..............................................以下有N条数据


我现在要筛选出 :
 
每周一 至周五 下午17点以后到 第二天 08点前 的数据 怎么写?

每周一 至周五 早上08点以后到 下午 17 点前 的数据 怎么写?

求高高手!!!!!! 非常急

------解决方案--------------------
SQL code

if object_id('test')is not null
drop table test
go
create table test(
ddd datetime,
A int,
B int,
C int
)
go
insert test
select '2012-05-26 01:15:45',23,78,98 union all
select '2012-05-27 02:15:45',23,78,98 union all
select '2012-05-28 03:15:45',23,78,98 union all
select '2012-05-29 04:15:45',23,78,98 union all
select '2012-05-30 05:15:45',23,78,98 union all
select '2012-05-31 06:15:45',23,78,98 union all
select '2012-06-01 07:15:45',23,78,98 union all
select '2012-06-02 08:15:45',23,78,98 union all
select '2012-06-03 09:15:45',23,78,98 union all
select '2012-06-04 10:15:45',23,78,98 union all
select '2012-06-05 11:15:45',23,78,98 union all
select '2012-06-06 12:15:45',23,78,98 union all
select '2012-06-07 13:15:45',23,78,98 union all
select '2012-06-08 14:15:45',23,78,98 union all
select '2012-06-09 12:15:45',23,78,98 union all
select '2012-06-10 16:15:45',23,78,98 union all
select '2012-06-11 17:15:45',23,78,98 union all
select '2012-06-12 18:15:45',23,78,98 union all
select '2012-06-13 19:15:45',23,78,98 union all
select '2012-06-14 20:15:45',23,78,98 union all
select '2012-06-15 21:15:45',23,78,98 union all
select '2012-06-16 22:15:45',23,78,98 union all
select '2012-06-17 23:15:45',23,78,98 union all
select '2012-06-18 00:15:45',23,78,98
go
--每周一至周五下午17点以后到第二天08点前
select datepart(wk,GETDATE())
select 
    CONVERT(varchar(19),ddd,120) as ddd,
    A,B,C
from
    test    
where 
    DATEPART(W,ddd) between 2 and 6
    --and DATEPART(WK,ddd)=datepart(wk,GETDATE())
    and (cast(CONVERT(varchar(8),ddd,24) as time)>='17:00:00' 
    or cast(CONVERT(varchar(8),ddd,24) as time)<='08:00:00')
/*
ddd    A    B    C
2012-05-28 03:15:45    23    78    98
2012-05-29 04:15:45    23    78    98
2012-05-30 05:15:45    23    78    98
2012-05-31 06:15:45    23    78    98
2012-06-01 07:15:45    23    78    98
2012-06-11 17:15:45    23    78    98
2012-06-12 18:15:45    23    78    98
2012-06-13 19:15:45    23    78    98
2012-06-14 20:15:45    23    78    98
2012-06-15 21:15:45    23    78    98
2012-06-18 00:15:45    23    78    98
*/
--每周一 至周五 早上08点以后到 下午 17 点前 的数据 怎么写?
select 
    CONVERT(varchar(19),ddd,120) as ddd,
    A,B,C
from
    test    
where 
    DATEPART(W,ddd) between 2 and 6
    --and DATEPART(WK,ddd)=datepart(wk,GETDATE())
    and CONVERT(varchar(8),ddd,24) between '08:00:00' and '17:00:00'
/*
ddd    A    B    C
2012-06-04 10:15:45    23    78    98
2012-06-05 11:15:45    23    78    98
2012-06-06 12:15:45    23    78    98
2012-06-07 13:15:45    23    78    98
2012-06-08 14:15:45    23    78    98
*/