SQL排名超过两个表

时间:2014-07-12 15:25:58

标签: sql postgresql

我有两个用户排名表。 表 rankingA rankingB 。 每个表都有列:

  • USER_ID
  • GROUP_ID

点数越高,用户/群组的排名越高......

现在我尝试获得排名有我的组的问题的组排名。 到目前为止我有这个SQL:

select sum(ra.points) as rapoints, sum(rb.points) as rbpoints from public.rankinga ra
LEFT JOIN public.rankingb rb ON ra.group_id=rb.group_id and ra.user_id=rb.user_id where
ra.group_id=200;

它返回组200的rankinga和rankinb中的点数。 我如何获得该组的排名?我尝试过: row_number()OVER(ORDER BY sum(rb.points)DESC)AS rankb 但得到了错误的结果。

我对group_id 200的预期结果是:

rapoints,rbpoints,rarank, rbrank
420,        10,     3,  same points as group_id 300 so rbrank 2 or 3

我怎么能得到这个?

设置

CREATE TABLE rankinga
(
user_id bigint,
group_id bigint,
points integer
)
CREATE TABLE rankingb
(
user_id bigint,
group_id bigint,
points integer
)
insert into public.rankinga (user_id,group_id,points) values (1,100,120),(2,100,300),  (3,100,20),(4,200,300),(5,200,120),(6,300,600);
insert into public.rankingb (user_id,group_id,points) values (1,100,5),(2,100,3),(3,100,10),(4,200,2),(5,200,8),(6,300,10);

1 个答案:

答案 0 :(得分:1)

我认为您希望使用union all,聚合和窗口函数执行此操作。加入表可能会错过行(如果用户在一个表中但不在另一个表中)或超过计数(如果您加入组)。所以这可能会做你想要的:

select group_id, sum(rapoints) as rapoints, sum(rbpoints) as rbpoints,
       sum(rapoints) + sum(rbpoints) as points,
       dense_rank() over (order by sum(rapoints) + sum(rbpoints) desc) as ranking
from ((select ra.group_id, sum(ra.points) as rapoints, 0 as rbpoints
       from public.rankinga ra
       group by ra.group_id
      ) union all
      (select rb.group_id, 0, sum(rb.points) as rbpoints
       from public.rankingb rb
       group by rb.group_id
      )
     ) ab
group by group_id;

如果您只想选择一个组,请将其放入子查询(或CTE)中,然后选择该组。

Here是一个SQL小提琴。

编辑:

如果您只想要一个组的结果,则仍需要计算所有组的值。所以:

select ab.*
from (<above query here>) ab
where group_id = 200;