简体   繁体   中英

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?

(On SQL Server 2014)

You can use row_number() function :

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.

If all your time are zeroed all you do need is to get everything where DATEPART is first day.

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.

I would use the day() function:

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() . The standard function is 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() . 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.

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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