【问题标题】:Select 5 latest rows of each column pairSelect 5 latest rows of each column pair
【发布时间】:2022-12-01 22:59:16
【问题描述】:

I've got a big table (>1m. rows) with a structure similar to this one:

ID foreign_key_1 foreign_key_2 clicks installs created_at
1 01 01 2 0 2022-11-10
2 01 02 54 12 2022-11-10
3 01 01 9 0 2022-11-11
4 01 02 85 20 2022-11-11
5 01 01 3 1 2022-11-12
6 01 02 8 0 2022-11-12
7 01 01 6 0 2022-11-13
8 01 02 221 60 2022-11-13
9 01 01 61 10 2022-11-14
10 01 02 75 17 2022-11-14
11 01 01 58 8 2022-11-15
12 01 02 9 0 2022-11-15
13 01 01 10 1 2022-11-16
14 01 02 25 0 2022-11-16

How would I be able to select the latest 5 rows of every unique pair of foreign_key_1 and foreign_key_2, based on their created_at dates? And is that even possible?

I've tried experimenting with partitions and grouping but I'm a begginer at writing mySQL syntax and complex queries so I haven't been able to figure it out.

【问题讨论】:

    标签: mysql mariadb


    【解决方案1】:

    One possible solution would be to use the row_number() window function where you partition by foreign_key_1 and foreign_key_2, and order the partitions by created_at in descending order:

    with row_nums as (
      select
        *,
        row_number() over (
          partition by foreign_key_1, foreign_key_2 order by created_at desc
        ) as rn
      from your_table
    )
    
    select *
    from row_nums
    where rn <= 5
    

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 2020-01-19
      • 2012-02-05
      • 1970-01-01
      • 2022-12-01
      • 2022-11-09
      • 2021-11-30
      • 2021-12-30
      • 2010-09-23
      相关资源
      最近更新 更多