日期:2014-05-17  浏览次数:20573 次

求一个时间段范围的SQL语句
表中有字段:begindate(起始时间) enddate(终止时间)

输入一个时间范围如:2012-1-1 到 2012-12-30

SQL语句把表中符合这个时间范围的记录都查询出来.
 
------解决方案--------------------
select * from tb where (begindate>='2012-1-1' and enddate<='2012-12-31') Or (begindate<='2012-1-1' and enddate>='2012-12-31') Or (begindate>'2012-1-1' and begindate<'2012-12-31') Or (enddate>'2012-1-1' and enddate<'2012-12-31')
------解决方案--------------------
两种情况都行:
1:数据库中记录的开始时间比给定的结束时间小
2:数据库中记录的结束时间比给定的开始时间大

--racer
if object_id('racer','u') is not null
drop table racer

create table racer
(
id int primary key,
name nvarchar(20),
team nvarchar(20),
begindate date,
enddate date
)
go
insert into racer values
(1001,'name1','team1','2012-02-12','2012-07-09'),
(1002,'name2','team2','2012-03-12','2012-08-09'),
(1003,'name3','team3','2012-04-12','2012-09-09'),
(1004,'name4','team4','2012-05-12','2012-10-09'),
(1005,'name5','team5','2012-06-12','2012-11-09'),
(1006,'name6','team6','2012-07-12','2012-12-09')

go


--SQL
declare @date1 date
declare @date2 date

set @date1='2012-04-23'
set @date2='2012-11-23'

select *From racer 
where begindate<@date2 or enddate>@date1

--结果集
--1001 name1 team1 2012-02-12 2012-07-09
--1002 name2 team2 2012-03-12 2012-08-09
--1003 name3 team3 2012-04-12 2012-09-09
--1004 name4 team4 2012-05-12 2012-10-09
--1005 name5 team5 2012-06-12 2012-11-09
--1006 name6 team6 2012-07-12 2012-12-09

------解决方案--------------------
说下这个的逻辑吧,这个逻辑好多知道答案了也不容易理清

把时间分为三段
2012-1-1前,2012-1-1 到 2012-12-30,2012-12-30后

现在需要begindate(起始时间) 到enddate(终止时间)的时间段与2012-1-1 到 2012-12-30有交集
其反命题就是 begindate(起始时间) 到enddate(终止时间)全部落在另外两段

另外两段的写法分别是:ENDdate<'2012-1-1' 和 begindate>'2012-12-31'
那我们要的就是NOT (ENDdate<'2012-1-1' OR begindate>'2012-12-31')
逻辑变换下就是 ENDdate>='2012-1-1' AND begindate<='2012-12-31'