简体   繁体   中英

SQL Query: Return value starting 28 days from parameter date to 56 days after parameter date

I have a query that allows me to return the number of events by EventID that occur from a parameter date (@STARTDATE) to 28 days previous. I would like to be able to return the number of events that occur in the previous 28 days.

COUNT (DISTINCT (CASE when EventID between  DATEADD(YEAR,-0,DATEADD(DAY, DATEDIFF(DAY, 0, @STARTDATE), -28)) and DATEADD(Year,-0,@STARTDATE) then EVentID END)) TwentyEightDays

I need to be able to run a similar query where the EVENTID count starts at 29 days from @STARTDATE to 56 days after @STARTDATE.

Any help is appreciated.

To count events from 28 days before to a given date, I would use:

COUNT(DISTINCT CASE WHEN eventdate >= DATEADD(day, -28, @StartDate) AND
                         eventdate <= @startdate
                    THEN EventId
               END) as TwentyEightDays

For 29 days to 56 days after:

COUNT(DISTINCT CASE WHEN eventdate >= DATEADD(day, 29, @StartDate) AND
                         eventdate <= DATEADD(day, 56, @StartDate)
                    THEN EventId
               END)

Note: This assumes that you have a column for the date in question. I doubt that is the EventId .

The numbers were reverse order but this query worked:

COUNT(DISTINCT CASE WHEN eventdate >= DATEADD(day, -56, @StartDate) AND eventdate <= DATEADD(day, -29, @StartDate) THEN EventId END)

Thank you to Gordon for this help!

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