SQL查询仅在每个月的第一天提取一条记录

时间:2018-07-16 17:54:01

标签: sql sql-server tsql

我有一张桌子,每天有一条记录。例如。 (这只是表格的日期列)

2018-07-08 03:00:00
2018-07-07 03:00:00
2018-07-06 03:00:00
2018-07-05 03:00:00
2018-07-04 03:00:00
2018-07-03 03:00:00
2018-07-02 03:00:00
2018-07-01 03:00:00
2018-06-30 03:00:00
2018-06-29 03:00:00

这些数据可以追溯到几年前

我只想提取表中所有月份的每月第一天记录。

执行此操作的SQL是什么?

(在SQL Server 2014上)

4 个答案:

答案 0 :(得分:1)

您可以使用row_number()函数:

select *
from (select *, row_number() over (partition by datepart(year, date), datepart(month, date) order by datepart(day, date)) seq
      from table
     ) t
where seq = 1;

也许您还需要year子句中的partition

答案 1 :(得分:1)

如果您所有的时间都归零,那么您要做的就是获得DATEPART是第一天的一切。

select * from dbo.MyTable mt where DATEPART(day, mt.MyDate) = 1

如果每天排一排,它将起作用。当然,如果您每天有多于一行,则需要使用DISTINCT或聚合。

答案 2 :(得分:1)

我将使用day()函数:

select t.*
from t
where day(t.MyDate) = 1;

此数据库和datepart()都不是ANSI / ISO标准,但是还有其他支持day()的数据库。标准函数为extract(day from t.MyDate)

如果您想要表中每个月的第一条记录-但是对于某些月份来说,可能不是第一天-那么您可以使用row_number()。一种方法是:

select top (1) with ties t.*
from t
order by row_number() over (partition by year(mydate), month(mydate) order by day(mydate) asc);

答案 3 :(得分:0)

尽管已回答了该问题,但您也可以使用MS SQL中的日期。

  create table  #temp (dates date) 

 insert into #temp values  ('2018-01-02'),('2018-01-05'), ('2018-01-09'), ('2018-01-10')

 select * from #temp 

 dates
 2018-01-02
 2018-01-05
 2018-01-09
 2018-01-10

 You can use this to get beginning of the month 

     select DATEFROMPARTS(year(dates), month(dates), 01) Beginningofmonth  from #temp 
     group by DATEFROMPARTS(year(dates), month(dates), 01)

 Output: 
 Beginningofmonth
 2018-01-01
相关问题