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

新手求助
怎样取得每个月最后一个星期天是几号?
语句:SQL server 2008


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

declare @year int=2011 

;with cte as 
(
    select DATEADD(DAY,number,LTRIM(@year)+'0101') mon
    from master..spt_values 
    where type='p' and number >=0
     and DATEADD(DAY,number,LTRIM(@year)+'0101')<LTRIM(@year+1)+'0101'
     and datepart(weekday,DATEADD(DAY,number,LTRIM(@year)+'0101'))=7
)
select * from cte t
where not exists(select * from cte where MONTH(mon)=MONTH(t.mon) and mon>t.mon)

mon
-----------------------
2011-01-30 00:00:00.000
2011-02-27 00:00:00.000
2011-03-27 00:00:00.000
2011-04-24 00:00:00.000
2011-05-29 00:00:00.000
2011-06-26 00:00:00.000
2011-07-31 00:00:00.000
2011-08-28 00:00:00.000
2011-09-25 00:00:00.000
2011-10-30 00:00:00.000
2011-11-27 00:00:00.000
2011-12-25 00:00:00.000

(12 row(s) affected)