2016-11-18 70 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'