简体   繁体   中英

Selecting Dynamic date range in sql

I have a query which bring the data based on their Activity date. The query goes like:

where al.ACTIVITY_DATE between '2017-01-01 00:00:00.000' and '2018-12-01 00:00:00.000'

It select all the activity falls under this data range.

Now as its 2019 i need to make changes on my date range as 2019-12-01 00:00:00:.000 .

What i don't want to do is to make changes every year on that report manually. Is it possible to select data of last 2 years along with the data of this year till 31st dec 2019?

Just do this:

WHERE al.ACTIVITY_DATE BETWEEN DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))
                           AND DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1)

This will make it the last two years dynamically.

This is the start of the previous year

DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))

This is the end of the current year.

DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1)

I think this is the simplest way to derive the beginning of last year:

DECLARE @start date = DATEFROMPARTS(YEAR(GETDATE())-1,1,1);

-- 2018-01-01

And then this is the simplest way to do a full date range queries for last year and this year, without worrying about the data types, rounding, etc. ( read this to see why BETWEEN is a bad idea ).

...
WHERE al.ACTIVITY_DATE >= @start 
  AND al.ACTIVITY_DATE <  DATEADD(YEAR, 2, @start); -- 2020-01-01

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