日期:2014-05-19  浏览次数:20453 次

一个sql日期段查询问题
数据库里有两个字段为日期:  
客户     开始日期         结束日期       消费
205       2007-6-1         2007-6-15       50
205       2007-6-16       2007-6-20       20
205       2007-6-21       2007-6-25       10
现在需要查询日期段为2007-6-5至2007-6-19的纪录,得到前两条的纪录,句子应该怎么写呢?

------解决方案--------------------
select * from tablename
where 结束日期> = '2007-6-5 '
and 开始日期 <= '2007-6-19 '

------解决方案--------------------
declare @stardate varchar(10),@enddate varchar(10)
select * from
(
select top 1 * from table where 开始日期 <= @stardate order by 开始日期 desc
union all
select top 1 * from table where 开始日期 <= @enddate order by 开始日期 desc
union all
select * from table table where 开始日期 between @stardate and @enddate
)A
order by A.開始時間
------解决方案--------------------

create table #r (客户 int, 开始日期 datetime, 结束日期 datetime )
insert into #r
select 205 , '2007-6-1 ' , '2007-6-15 ' union all
select 205 , '2007-6-16 ', '2007-6-20 ' union all
select 205 , '2007-6-21 ' , '2007-6-25 '

select * from #r where 开始日期 between '2007-6-5 ' and '2007-6-19 ' or 结束日期 between '2007-6-5 ' and '2007-6-19 '