【问题标题】:SQL find the 2 highest score for each countrySQL 查找每个国家的 2 个最高分
【发布时间】:2021-12-04 11:22:06
【问题描述】:

我有两个表: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

【问题讨论】:

  • 在您的子查询中,通过 query_score desc 将其更改为按国家/地区顺序分区还将您的 where 子句更改为 score_rank

标签: sql partition row-number


【解决方案1】:

这可以通过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/

【讨论】:

    猜你喜欢
    • 2016-11-15
    • 2021-12-22
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    相关资源
    最近更新 更多