Skip to content
Advertisement

Select all completed months until certain date in SQL Server

I have a query that returns certain time series information. But since I am doing analysis for each completed month, I would like to ignore the last month information so it does not contaminate the data. So the actual data would look similar to this:

       T.Date          T.Profit
     1/1/2016          15
     1/15/2016         25
     1/29/2016          5
     2/03/2016          10

So, I was thinking in doing something like:

where T.Date <= Datefromparts(Year(max(T.Date)),Month(Max(T.Date)),1)

And I would receive something like:

       T.Date          T.Profit
     1/1/2016          15
     1/15/2016         25
     1/29/2016          5

But seems like this is not the way.

Advertisement

Answer

I see nothing wrong with your approach:

select t.*
from (select t.*, max(date) over () as max_date
      from t
     ) t
where t.date < datefromparts(year(max_date), month(max_date), 1);

Perhaps more colloquially, this could be written as:

select t.*
from t
where t.date < (select dateadd(day, 1 - day(max(date)), max(date))
                from t
               );
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement