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

新手求助SQL
用一个SELECT查出本月的最后一个星期天是几号?
越简洁越好!谢谢!

工具:SQL SERVER 2008


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


--本月的
select max(convert(varchar(10),getdate()+number,120))
from master..spt_values 
where type='p' 
and  DATEPART (dw,getdate()+number)=1
and  datediff(mm,getdate()+number,getdate())=0

------解决方案--------------------
SQL code
set datefirst 1


;with cte as 
(
    select DATEADD(DAY,number,convert(varchar(6),GETDATE(),112)+'01') mon
    from master..spt_values 
    where type='p' and number >=0
     and DATEADD(DAY,number,convert(varchar(6),GETDATE(),112)+'01')<ltrim(YEAR(GETDATE()))+right('00'+ltrim(month(GETDATE())+1),2)+'01'
     and datepart(weekday,DATEADD(DAY,number,convert(varchar(6),GETDATE(),112)+'01'))=7
)
select * from cte t
where not exists(select * from cte where MONTH(mon)=MONTH(t.mon) and mon>t.mon)

mon
-----------------------
2011-02-27 00:00:00.000

(1 row(s) affected)