在Postgresql中返回每组的前三个结果(每周前三名)

0 postgresql group-by function

 CREATE TABLE games
    (
      idg serial NOT NULL,
      nation character(3),
      points integer,
      datag date,
      CONSTRAINT pk_games PRIMARY KEY (idg )
)

idg    nation  points      dateg
1      ita      12      2011-10-10
2      fra       9      2011-10-11
3      ita       4      2011-10-12
4      fra       8      2011-10-11
5      ger      12      2011-10-12
6      aut       6      2011-10-10
7      ita      11      2011-10-17
8      ita      10      2011-10-18
9      fra       9      2011-10-19
10     ger      15      2011-10-19
11     fra      16      2011-10-18
Run Code Online (Sandbox Code Playgroud)

我希望显示最多三个星期的总数.我明白我不能使用max(sum(points),所以我做了下一个查询:

select extract(week from datag) as "dateg", nation, sum(points) as "total"
from games
group by dateg, nation
order by dateg asc, total desc limit 3
Run Code Online (Sandbox Code Playgroud)

但这些只返回前三个总数.我怎样才能每周都做到这一点(每组的前三个总数,​​这将是一种"每周前三名")?任何想法?

在Postgresql 9中工作.

提前致谢.

mu *_*ort 5

使用窗口功能:

select idg, nation, points, wk, r
from (
    select idg, nation, points, extract(week from datag) as wk,
           row_number() over (partition by extract(week from datag) order by points desc) as r
    from games
) as dt
where r <= 3
Run Code Online (Sandbox Code Playgroud)

根据需要调整SELECT.nation如果您想要独特的排名,可以在PARTITION中添加ORDER BY.

如果您想首先计算每个国家/地区的每周积分,那么您只需添加另一个派生表并稍微调整列名称:

select nation, wk, wk_points, rn
from (
    select nation, wk, wk_points,
           row_number() over (partition by wk order by wk_points desc) as rn
    from (
        select nation, extract(week from datag) wk, sum(points) wk_points
        from games
        group by wk, nation
    ) as dt_sum
) as dt
where rn <= 3
Run Code Online (Sandbox Code Playgroud)