简体   繁体   中英

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. 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. This scans the table 2 times instead of 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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