聚合内部查询SQL优化

问题描述 投票:1回答:1

我有3张桌子:

create table users
    (
        user_id varchar(50),
        birth_year int,
        country varchar(50)
    )


create table notifications 
    (
        status varchar(50), 
        user_id varchar(50), 
        created_date datetime
    )

create table transactions
    (
        transaction_id varchar(50),
        user_id varchar(50),
        created_date datetime
    )

[我想做的是让收到通知的所有用户,通知到达前7天与通知之后7天的平均交易额有何不同按国家和年龄段到达。

我做了以下工作:

select q.country
, case when q.age <= 18 then '<= 18'
    when q.age <= 30 then '19 - 30'
    when q.age <= 45 then '31 - 45'
    when q.age <= 60 then '46 - 60'
    else '> 60' end as age_group
, AVG(q.prev_transactions*1.0) as avg_prev_transactions, AVG(q.post_transactions*1.0) as avg_post_transactions
from (
    select n.user_id, n.created_date, u.country, (2019 - u.birth_year) as age
    , count(distinct prev.transaction_id) as prev_transactions, count(distinct post.transaction_id) as post_transactions
    from notifications n
    left outer join transactions post on n.user_id = post.user_id and post.created_date > n.created_date and post.created_date < n.created_date + interval '7' day
    left outer join transactions prev on n.user_id = prev.user_id and prev.created_date < n.created_date and prev.created_date > n.created_date - interval '7' day
    left outer join users u on u.user_id = n.user_id
    where status = 'SENT'
    group by n.user_id, n.created_date, u.country, (2019 - u.birth_year)
    --order by n.user_id asc, n.created_date asc
    ) as q
group by q.country, case when q.age <= 18 then '<= 18'
    when q.age <= 30 then '19 - 30'
    when q.age <= 45 then '31 - 45'
    when q.age <= 60 then '46 - 60'
    else '> 60' end

我想知道是否有办法提高效率。

谢谢

sql postgresql metabase
1个回答
0
投票
您可以将它们放在每个子选择中,而不是作为联接。

select n.user_id, n.created_date, u.country, (2019 - u.birth_year) as age, (select count(*) from transactions post on n.user_id = post.user_id and post.created_date > n.created_date and post.created_date < n.created_date + interval '7' day) as post_transactions, ...

而且,为什么左派反对用户?对于没有用户的通知,可以获得什么可能有意义的输出?

© www.soinside.com 2019 - 2024. All rights reserved.