简体   繁体   中英

How to get the last seven days of one month's data in SQL?

I used below SQL to get last day of the month, but I need last seven days of the month:

DECLARE @dt as DATETIME = '7/29/2018'
DECLARE @LastDayOfTheMonth as DATETIME = DATEADD(DAY, -1, DATEADD(Month, 1, DATEADD(DAY,1 - DAY(@dt),@dt)))

SELECT @LastDayOfTheMonth

I could also use this SQL function in order to get above result, but I need last 7 days of any month's records.

SELECT EOMONTH('7/29/2018')

Just use DATEADD again to take 1 to 6 more days off @LastDayOfTheMonth.

SELECT @LastDayOfTheMonth, DATEADD(DAY,-1,@LastDayOfTheMonth), ..

If you want to return 7 values from a function, suggest making it a table function.

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