在postgresql中枚举

时间:2012-02-07 07:46:10

标签: sql postgresql

有没有办法在postgresql中枚举查询行?

我有这样的表:

Table players
id player_id game_id points

我想要这样的查询:

SELECT  game_id, <row_number in points group>, <array of ids> 
    FROM players WHERE game_id = %s 
    GROUP BY game_id, points; 

2 个答案:

答案 0 :(得分:3)

我不确定你要求的是什么。 “点组中的行号”是一个直接的window function应用程序,但我不知道“数组”是什么意思。

给出这样的日期:

 id | player_id | game_id | points 
----+-----------+---------+--------
  1 |         1 |       1 |      0
  2 |         1 |       2 |      1
  3 |         1 |       3 |      5
  4 |         2 |       1 |      1
  5 |         2 |       2 |      0
  6 |         2 |       3 |      0
  7 |         3 |       1 |      2
  8 |         3 |       2 |      3
  9 |         3 |       3 |      1

你可以通过以下方式获得每场比赛的排名:

select game_id, player_id, points,
       rank() over (partition by game_id order by points desc)
from players

这会给你这样的输出:

 game_id | player_id | points | rank 
---------+-----------+--------+------
       1 |         3 |      2 |    1
       1 |         2 |      1 |    2
       1 |         1 |      0 |    3
       2 |         3 |      3 |    1
       2 |         1 |      1 |    2
       2 |         2 |      0 |    3
       3 |         1 |      5 |    1
       3 |         3 |      1 |    2
       3 |         2 |      0 |    3

答案 1 :(得分:3)

这应该是您正在搜索的内容:

 SELECT game_id
 , row_number() OVER (PARTITION BY game_id ORDER BY points) AS num
 , array_agg(id) AS ids
 FROM players WHERE game_id = %s 
 GROUP BY game_id, points
 ORDER BY game_id, points