简体   繁体   中英

Sql Query + fetch first 2 records of every month

I have a large set of data with the date as the primary key and there will be records for most of the days. Is it possible to write an SQL query to fetch records for the first 2 days of every month?

For example, the table may have data for the 1st to 31st of January, but the 3rd to 25th of February. In this case, the query needs to fetch records for the 1st and 2nd of January, and the 3rd and 4th of February.

I could think of a procedure to do the same. Or else, can fetch records and handle the filtering in server-side PHP script. But I do not think it is easy to do this in SQL.

Appreciated your help. Thanks.

(Mysql Version: 8)

You can use ROW_NUMBER(). For example assuming d is the date column

select * 
from (
   select *, row_number() over(partition by Year(d), Month(d) order by Day(d)) n
   from yourtable
) t
where n <=2

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