2016-11-18 69 views
0

我有一个表,我需要从一切与此规则选择:Postgres的内部查询性能

id = 4524522000143 and validPoint = true 
and date > (max(date)- interval '12 month') 
-- the max date, is the max date for this id 

解释规则:我必须让所有的寄存器和计数他们,他们必须至少1年从最新的注册表中删除旧的。

这是我的实际查询:

WITH points as (
    select 1 as ct from base_faturamento_mensal 
    where id = 4524522000143 and validPoint = true 
    group by id,date 
    having date > (max(date)- interval '12 month') 
) select sum(ct) from points 

是否有这种更有效的方法?

回答

2

那么你的查询使用的技巧包括在HAVING子句中的未聚合的列,但我并没有觉得它特别糟糕。这似乎很好,但没有EXPLAIN ANALYZE <query>输出,我不能说更多。

要做的一件事是你可以摆脱CTE并在同一查询中使用count(*),而不是返回1,然后在其上运行sum

select count(*) as ct 
from base_faturamento_mensal 
where id = 4524522000143 
    and validPoint = true 
group by id, date 
having date > max(date) - interval '12 months'