SQL 为每个国家找到 2 个最高分

SQL find the 2 highest score for each country

我有两个表:maps_query 和 map_time,如下所示:

CREATE TABLE maps_query (
    id             int 
    day            varchar
    search_query   varchar
    country        varchar
    query_score    int
)

CREATE TABLE map_time (
    id   int
    am_pm  varchar
)

问题是为每个国家找到 2 个最高分。所需的输出如下所示:

country  search_query  query_score
CA        Target       1000
CA        Store        900
FR        Eiffiel      1500
FR        London       800

我试图使用 row_number() 结束,但不知道如何完成查询。

Select t1.country, t1.search_query, t1.score_rank, 
from (select *, (row_number() over(partition by country order by query_score) as score_rank from maps_search) t1
where score_rank = 1 and score_rank=2

这可以通过 rank() 而不是 row_number() 来实现。

select 
  * 
from 
  (
    select 
      *, 
      rank() over (
        PARTITION by country 
        order by 
          query_score desc
      ) 
    from 
      maps_query
  ) q 
where 
  rank <= 2;

一篇很好的参考文章:https://spin.atomicobject.com/2016/03/12/select-top-n-per-group-postgresql/