简体   繁体   English

在SQL中选择动态日期范围

[英]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 . 现在是2019年,我需要在我的日期范围内进行更改,即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? 是否可以选择最近两年的数据以及截至2019年12月31日的今年数据?

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 ). 然后,这是对去年和今年进行全日期范围查询的最简单方法,而不必担心数据类型,舍入等问题(请阅读BETWEEN以了解BETWEEN为什么是个坏主意 )。

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

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

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