简体   繁体   English

在sql的日期范围内选择动态日期

[英]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 .例如,如果我们今天使用这个查询 (20201106)(格式:yyyymmdd),那么第二个日期应该是20191105

For more clarity: when I run this query today (20201106) my query should fetch results from date range:为了更清楚:当我今天(20201106)运行这个查询时我的查询应该从日期范围获取结果:

WHERE 
    date BETWEEN 20190101 AND 20191105

When I run this query tomorrow (20201107), my query should fetch results from the date range:当我明天(20201107)运行这个查询时,我的查询应该从日期范围中获取结果:

WHERE 
    date BETWEEN 20190101 AND 20191106

How can I do this?我怎样才能做到这一点?

Can anyone help?任何人都可以帮忙吗?

you can use dateadd() with getdate()您可以将dateadd()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.还记得使用convert()将日期格式修改为您想要的格式。

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.这从去年年初和 1 年零 1 天前开始过滤。

Note that I changed the filtering strategy to use half-open intervals rather than between .请注意,我改变了过滤策略,使用半开区间,而不是between This is somehow more flexible, as it would properly handle a time component in in date , if any, and simplifies the offsetting logic.这在某种程度上更灵活,因为它可以正确处理date的时间组件(如果有),并简化了偏移逻辑。

Note also that getdate() has a time component, that needs to be removed while offsetting to implement your logic.另请注意, getdate()有一个时间组件,需要在偏移时将其删除以实现您的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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