[英]How can I get the last 12 months from the current date PLUS extra days till 1st of the last month retrieved
Getting the last 12 months from a specific date is easy and can be retrieved by the following command in SQL-server. Its answer is 2014-08-17.从特定日期获取最近 12 个月很容易,可以通过 SQL-server 中的以下命令检索。它的答案是 2014-08-17。
select Dateadd(Month, -12, '2015-08-17')
What I want is to get the last 12 months but ending at 2014-08- 01 (in the above case) instead of any where in the middle of the month.我想要的是过去 12 个月但结束于 2014-08-01(在上述情况下)而不是月中的任何地方。
Using DATEADD
and DATEDIFF
: 使用
DATEADD
和DATEDIFF
:
DECLARE @ThisDate DATE = '20150817'
SELECT DATEADD(YEAR, -1, DATEADD(MONTH, DATEDIFF(MONTH, '19000101', @ThisDate), '19000101'))
For more common date routines, see this article by Lynn Pettis. 有关更常见的日期例程,请参阅Lynn Pettis 撰写的这篇文章 。
To use in your WHERE
clause: 要在
WHERE
子句中使用:
DECLARE @ThisDate DATE = '20150817'
SELECT *
FROM <your_table>
WHERE
<date_column> >= DATEADD(YEAR, -1, DATEADD(MONTH, DATEDIFF(MONTH, '19000101', @ThisDate), '19000101'))
SELECT dateadd(month,datediff(month,0,getdate())-12,0)
Result is 结果是
-----------------------
2014-08-01 00:00:00.000
So the where clause should be 所以where子句应该是
WHERE datecol >=dateadd(month,datediff(month,0,getdate())-12,0)
to get all data starting from jan 01 of last year's same month 从去年同月的01月1日开始获取所有数据
If you want all the records since the first day of the current month last year, then you can use: 如果您想要自去年当月第一天以来的所有记录,那么您可以使用:
where <somedate> >= dateadd(day, 1 - day(dateadd(month, -12, getdate()),
dateadd(month, -12, getdate()))
For all days except Feb 29th, you can use the simpler: 对于除 2月29日之外的所有日子,您可以使用更简单的:
where <somedate> >= dateadd(day, 1 - day(getdate()),
dateadd(month, -12, getdate))
I would use this in order to consider days and not only months as this can cause issues:我会使用它来考虑几天而不是几个月,因为这可能会导致问题:
SELECT *
FROM <your_table>
WHERE DATEDIFF(DAY,date_column, GETDATE()) <= 365
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.