我有一个事件表,其中包含以下列user_id
,points
,created
。我需要的是获得给定user_id
的给定月份,总积分和总排名的所有积分。我需要在单个查询中执行此操作,从而导致以下尝试:
select
e.user_id,
sum(e.points) as total_points,
(select sum(points) from event where user_id = 1 and extract(month from created) = 1) as month_points,
(select rank from (select user_id as id, rank() over (order by sum(points) desc) from event group by user_id) as rank where id = 1)
from
event pte
where
e.user_id = 1
group by
e.user_id
;
我想问的是:
rank
功能是否足够可靠还是被误用了?答案 0 :(得分:1)
假设postgresql版本大于或等于9.4,您可以使用聚合filter
子句来避免month_points
和rank
的子选择:
select * from
(select
e.user_id,
sum(e.points) as total_points,
sum(points) filter (where extract(month from created) = 1) as month_points,
rank() over (order by sum(points) desc)
from
event e
group by
e.user_id
) as inner_query
where user_id = 1;