简体   繁体   English

需要帮助在Postgres中用窗口函数替换子查询

[英]Need help replacing subqueries with window functions in Postgres

I have a query that returns the results I want, however it takes 3 full table scans because of the subqueries. 我有一个查询,该查询返回所需的结果,但是由于子查询,它需要进行3次全表扫描。 My attempts to turn this into window functions have not worked. 我将其转换为窗口功能的尝试无效。 Thoughts? 思考?

SELECT a_day
    ,max(week_count)
    ,max(month_count)
FROM (
    SELECT DISTINCT date_trunc('day', created_at) AS a_day
        ,(
            SELECT count(*)
            FROM accounts AS wk
            WHERE wk.created_at BETWEEN (a.created_at - INTERVAL '7 days')
                    AND a.created_at
            ) AS week_count
        ,(
            SELECT count(*)
            FROM accounts AS wk
            WHERE wk.created_at BETWEEN (a.created_at - INTERVAL '30 days')
                    AND a.created_at
            ) AS month_count
    FROM accounts a
    ORDER BY a_day
    ) AS sub_1
GROUP BY a_day
ORDER BY a_day
with sub_1 as
(select date_trunc('day', created_at) AS a_day, count(*) as week_count
 from accounts
 where created_at BETWEEN (created_at - INTERVAL '7 days') and created_at
 group by date_trunc('day', created_at))
,sub_2 as 
(select date_trunc('day', created_at) AS a_day, count(*) as month_count
 from accounts
 where created_at BETWEEN (created_at - INTERVAL '30 days') and created_at
 group by date_trunc('day', created_at))
 select sub_1.a_day, max(sub_1.week_count), max(sub_2.month_count)
 from sub_1 join sub_2 on sub_1.a_day = sub_2.a_day
 group by sub_1.a_day

Try using the Common table expressions and see if you can get the performance gain. 尝试使用Common表表达式,看看是否可以获得性能提升。 This scans the table 2 times instead of 3. 这将扫描表2次而不是3次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM