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

SQL 中在一段日期内找到不存在的日期中最大的 50分
比如 SQL这段日期 2012-09-01 至 2012-09-13
已有的日期
2012-09-01
2012-09-02
2012-09-10
2012-09-13
需要找到
2012-09-12 
 

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

    create table tb (date_time datetime)
    insert tb select '2012-09-01' union select '2012-09-02' union select '2012-09-10' union select '2012-09-13' 
    
    go
    select * from tb
    /*
    date_time
2012-09-01 00:00:00.000
2012-09-02 00:00:00.000
2012-09-10 00:00:00.000
2012-09-13 00:00:00.000
    */
declare @sdate datetime 
declare @edate datetime 
set @sdate = '2012-09-01' 
set @edate = '2012-09-13' 


select MAX (dd)dd from (
select 
    convert(varchar(10),dateadd(dd,num,@sdate),120) dd
from 
    (select isnull((select count(1) from sysobjects where id <t.id),0) as num from sysobjects t) a 
where 
    dateadd(dd,num,@sdate) <=@edate )a 
    where dd not in (select date_time from tb )
  /*
  dd
2012-09-12
*/