SQL Last 6 Months

SQL Last 6 Months

For MS SQL Server, you can use:

where datetime_column >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6,
current_timestamp)), 0)

SQL Server Query Last 6 Months

You need to add this to your where clause, if I understand what you are after correctly:

and ar.[Report Date] > DATEADD(m, -6, GetDate())

Get past 6 months data from a table based on the recent date present in the column

with data as (
select *,
convert(date, '01-' + dt, 105) as converted_dt,
max(convert(date, '01-' + dt, 105)) over () as last_converted_dt
from T
)
select * from data
where converted_dt >= dateadd(month, -6, last_converted_dt);

The 105 comes from the list of date formats which can be found in the documentation for cast/convert. SQL Server can convert strings like Apr 2021 so a cast like below might also work (if you actually have four-digit years) but it's best to be explicit about the format as I did above.

cast(replace(dt, '-', ' ' as date)

Get first and last 6 months in year with timestamp in SQL

DATEFROMPARTS function can be used for that:

SELECT
DATEFROMPARTS(YEAR(GETDATE()),1,1) AS beginningOfYear,
DATEFROMPARTS(YEAR(GETDATE()),6,1) AS midOfYear

How to select last 6 months from news table using MySQL

Use DATE_SUB

 .... where yourdate_column > DATE_SUB(now(), INTERVAL 6 MONTH)

SQL query for getting data for the last 6 months grouped by month?

EDIT:
Over the hours I made a few corrections. Most notably I corrected the self join query to reflect my intentions and also added more details to better explain what is going on.

To my knowledge there are two ways about it (which are probably the same under the hood).

Also, please note that these solutions assume you have a month field already in place. If you have a date or timestamp field, you should take one extra preparation step.

[Addendum] To be more precise, I'd say that the ideal would be to have a date/timestamp field that is truncated/flattened to the first day of the month.

As an example,



Leave a reply



Submit