PostgreSQL查询性能和变化

时间:2015-05-27 08:15:20

标签: sql postgresql

我有一个事件表,其中包含以下列user_idpointscreated。我需要的是获得给定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
;

我想问的是:

  1. 此查询可以缓慢吗?
  2. 可以用其他方式做得更好吗?
  3. rank功能是否足够可靠还是被误用了?

1 个答案:

答案 0 :(得分:1)

假设postgresql版本大于或等于9.4,您可以使用聚合filter子句来避免month_pointsrank的子选择:

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;