繁体   English   中英

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

[英]SQL Query to only pull one record for first day of month, for every month

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

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

您可以使用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 in partition子句。

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

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

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

我将使用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);

尽管已经回答了该问题,但是您也可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM