简体   繁体   English

Sql 查询+获取每个月的前2条记录

[英]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?是否可以编写一个 SQL 查询来获取每个月前 2 天的记录?

For example, the table may have data for the 1st to 31st of January, but the 3rd to 25th of February.例如,该表可能包含 1 月 1 日至 31 日的数据,但包含 2 月 3 日至 25 日的数据。 In this case, the query needs to fetch records for the 1st and 2nd of January, and the 3rd and 4th of February.在这种情况下,查询需要获取 1 月 1 日和 2 日以及 2 月 3 日和 4 日的记录。

I could think of a procedure to do the same.我可以想到一个程序来做同样的事情。 Or else, can fetch records and handle the filtering in server-side PHP script.否则,可以在服务器端 PHP 脚本中获取记录并处理过滤。 But I do not think it is easy to do this in SQL.但我认为在 SQL 中做到这一点并不容易。

Appreciated your help.感谢您的帮助。 Thanks.谢谢。

(Mysql Version: 8) (Mysql 版本: 8)

You can use ROW_NUMBER().您可以使用 ROW_NUMBER()。 For example assuming d is the date column例如假设d是日期列

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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