Sql Query + fetch first 2 records of every month

Sql Query + fetch first 2 records of every month

Problem Description:

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)

Solution – 1

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
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.