简体   繁体   English

Select 从 MySQL 表中每年最多 1 条记录

[英]Select max 1 record per year from a MySQL table

I need to extract data from a MySQL table, but am not allowed to include a record if there's a previous record less than a year old.我需要从 MySQL 表中提取数据,但如果之前的记录不到一年,则不允许包含记录。

Given the following records, only the records 1 , 3 and 5 should be included (because record 2 was created 1 month after record 1, and record 4 was created 1 month after record 3):鉴于以下记录,只应包括记录1、35 (因为记录 2 是在记录 1 之后 1月创建的,而记录 4 是在记录 3 之后 1 个月创建的):

1   2019-12-21
2   2020-01-21
3   2021-12-21
4   2022-01-21
5   2023-12-21

I came up with the following non-functional solution:我想出了以下非功能性解决方案:

SELECT 
    * 
FROM 
    table t 
WHERE 
    (created_at > DATE_ADD(
        (SELECT 
            created_at 
        FROM 
            table t2 
        WHERE 
            t2.created_at < t.created_at 
        ORDER BY 
            t2.created_at 
        DESC LIMIT 1), INTERVAL 1 YEAR)

But this only returns the first and the last record, but not the third:但这只会返回第一条和最后一条记录,而不是第三条:

1   2019-12-21
5   2023-12-21

I know why: the third record gets excluded because record 2 is less than a year old.我知道为什么:第三条记录被排除在外,因为记录 2 不到一年。 But record 2 shouldn't be taken into account, because it won't make the list itself.但是不应该考虑记录 2,因为它本身不会成为列表。

How can I solve this?我该如何解决这个问题?

Using lag , assuming your MySql supports it, you can calculate the difference in months using period_diff使用lag ,假设您的 MySql 支持它,您可以使用period_diff计算月差

with d as (
  select * , 
    period_diff(extract(year_month FROM date),
      extract(year_month from lag(date,1,date) over (order by date))
    ) as m
  from t
 )
 select id, date
 from d
 where m=0 or m>12

Demo Fiddle 演示小提琴

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

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