Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 599
Mian Asbat Ahmad Avatar asked Aug 17 '15 11:08

Mian Asbat Ahmad


People also ask

How do I get last 12 months data?

How to Get Last 12 Months Sales Data in SQL. mysql> select * from sales where order_date> now() - INTERVAL 12 month; In the above query, we use system function now() to get current datetime. Then we use INTERVAL clause to filter those records where order_date falls after an interval of 12 months before present datetime ...

How do you subtract 6 months from current date in SQL?

We can use DATEADD() function like below to Subtract Months from DateTime in Sql Server. DATEADD() functions first parameter value can be month or mm or m, all will return the same result.

How do I get last 3 months data in SQL?

In SQL Server, you can use the DATEADD() function to get last 3 months (or n months) records.

How do I subtract one year from a date in SQL?

We can use DATEADD() function like below to Subtract Years from DateTime in Sql Server. DATEADD() functions first parameter value can be year or yyyy or yy, all will return the same result.


3 Answers

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 datecol >=dateadd(month,datediff(month,0,getdate())-12,0)

to get all data starting from jan 01 of last year's same month

like image 113
Madhivanan Avatar answered Sep 19 '22 22:09

Madhivanan


Using DATEADD and 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.


To use in your WHERE clause:

DECLARE @ThisDate DATE = '20150817'
SELECT *
FROM <your_table>
WHERE
    <date_column> >= DATEADD(YEAR, -1, DATEADD(MONTH, DATEDIFF(MONTH, '19000101', @ThisDate), '19000101'))
like image 28
Felix Pamittan Avatar answered Sep 23 '22 22:09

Felix Pamittan


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:

where <somedate> >= dateadd(day, 1 - day(getdate()),
                            dateadd(month, -12, getdate))
like image 22
Gordon Linoff Avatar answered Sep 21 '22 22:09

Gordon Linoff