簡體   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