简体   繁体   English

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

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

I have a table that has one record per day. 我有一张桌子,每天有一条记录。 Eg (this is just the date col of the table) 例如(这只是表格的日期列)

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

This data goes back a few years 这些数据可以追溯到几年前

I want to pull just the first day of month record, for all months in the table. 我只想提取表中所有月份的每月第一天记录。

What is the SQL to do that? SQL是做什么的?

(On SQL Server 2014) (在SQL Server 2014上)

You can use row_number() function : 您可以使用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;

Perhaps you also need year in partition clause. 也许您还需要year in partition子句。

If all your time are zeroed all you do need is to get everything where DATEPART is first day. 如果您所有的时间都归零,那么您要做的就是将DATEPART作为第一天的一切。

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

It will work if you got one row per day. 如果您每天有一行,它将起作用。 Off course you will need to use DISTINCT or an aggregation if you got more than one row per day. 当然,如果您每天有多于一行,则需要使用DISTINCT或聚合。

I would use the day() function: 我将使用day()函数:

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

Neither this nor datepart() are ANSI/ISO-standard, but there are other databases that support day() . 这个和datepart()都不是ANSI / ISO标准,但是还有其他支持day()数据库。 The standard function is extract(day from t.MyDate) . 标准函数是extract(day from t.MyDate)

If you want the first record in the table for each month -- but for some months, that might not be day 1 -- then you can use row_number() . 如果您想要表中每个月的第一条记录-但对于某些月份,可能不是第一天-那么您可以使用row_number() One method is: 一种方法是:

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

Though this has been answered, you can use date from parts in MS SQL as well. 尽管已经回答了该问题,但是您也可以使用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