简体   繁体   中英

Selecting Dynamic date in a date range of sql

This is what my query's date range is:

WHERE 
    date BETWEEN 20190101 AND [here date should come as last year YTD -1]

For example if we use this query today (20201106) (format:yyyymmdd), then the 2nd date should be 20191105 .

For more clarity: when I run this query today (20201106) my query should fetch results from date range:

WHERE 
    date BETWEEN 20190101 AND 20191105

When I run this query tomorrow (20201107), my query should fetch results from the date range:

WHERE 
    date BETWEEN 20190101 AND 20191106

How can I do this?

Can anyone help?

you can use dateadd() with getdate()

DATEADD(year,-1, GETDATE()) 

or other function that can get current database time but this should work. also remember to use convert() to modify the date format into what you want.

WHERE 
DATEADD(YEAR,-1, GETDATE()) -- One Day Before Today in the Last Year
AND 
DATEADD(yy, DATEDIFF(yy, 0, DATEADD(YEAR,-1, GETDATE())), 0) AS StartOfYear -- The Day 1 of the Last Year

I would phrase this as:

where date >= datefromparts(year(getdate()) - 1, 1, 1)
  and date <  dateadd(year, -1, convert(date, getdate()))

This filters from the start of last year and the 1 year and 1 day ago.

Note that I changed the filtering strategy to use half-open intervals rather than between . This is somehow more flexible, as it would properly handle a time component in in date , if any, and simplifies the offsetting logic.

Note also that getdate() has a time component, that needs to be removed while offsetting to implement your logic.

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