首页 > 解决方案 > 在 SQL Server 中选择特定日期之前的所有已完成月份

问题描述

我有一个返回某些时间序列信息的查询。但是由于我正在对每个完整的月份进行分析,因此我想忽略上个月的信息,以免污染数据。所以实际数据看起来类似于:

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

所以,我正在考虑做类似的事情:

在哪里T.Date <= Datefromparts(Year(max(T.Date)),Month(Max(T.Date)),1)

我会收到类似的东西:

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

但似乎这不是办法。

标签: sqlsql-server

解决方案


我认为您的方法没有任何问题:

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);

也许更通俗地说,这可以写成:

select t.*
from t
where t.date < (select dateadd(day, 1 - day(max(date)), max(date))
                from t
               );

推荐阅读