简体   繁体   中英

Get Mondays of the last two months from SQL Server 2008

If today is 10 JULY 2015 then what I need is a record set in SQL Server which has the following records

 6 JULY 2015
29 JUNE 2015
22 JUNE 2015
15 JUNE 2015
 8 JUNE 2015
 1 JUNE 2015
25 MAY  2015

Try this

;WITH dates AS 
(
    SELECT CONVERT(datetime,cast(month(getdate())-2 as varchar(2))+'/'+cast(day(getdate()) as varchar(2))+'/'+ cast(year(getdate()) as varchar(4))) as Date,' ' as eid
    UNION ALL
    SELECT DATEADD(d,1,[Date]),' ' as eid
    FROM dates 
    WHERE DATE < GETDATE()
)
select  datename(DD,dates.date)+' '+datename(MM,dates.date)+' '+ datename(YYYY,dates.date) from dates
where datename(dw,dates.date) = 'Monday'

With the following expression you get the last Monday:

CAST(GETDATE()-(@@DATEFIRST-1+DATEPART(weekday,GETDATE())) % 7+1 AS DATE)

Here we use @@DATEFIRST and DATEPART(weekday,...) to find the last MONDAY.

Then you should generate 8 (two months) rows sequence of days each of them -7 days prior the next. Here I've used CTE but you can use UNION or TOP 8 rows from existing (system or user) in your DB table to generate 8 rows.

;WITH CT(n) AS
(
    SELECT 0
    UNION ALL
    SELECT n+1 FROM CT WHERE n < 7
)
SELECT DATEADD(DAY,-n*7,
      CAST(GETDATE()-
           (@@DATEFIRST-1+DATEPART(weekday,GETDATE())) % 7+1 AS DATE))  as DT 
FROM CT ORDER BY n

Sqlfiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM