SQL 如何获取从当前日期到上个月第一天的最后 12 个月加上额外的天数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32049478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the last 12 months from the current date PLUS extra days till 1st of the last month retrieved
提问by Mian Asbat Ahmad
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在本月中旬在哪里(在上述情况下),而不是任何。
采纳答案by Felix Pamittan
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 articleby 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'))
回答by Madhivanan
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
获取从去年同月的 1 月 1 日开始的所有数据
回答by Gordon Linoff
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 exceptFeb 29th, you can use the simpler:
对于除2 月 29日以外的所有日子,您可以使用更简单的:
where <somedate> >= dateadd(day, 1 - day(getdate()),
dateadd(month, -12, getdate))