【发布时间】:2020-05-13 00:07:20
【问题描述】:
我有 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
我想知道是否有办法让它更高效。
谢谢
【问题讨论】:
-
你为什么要在这里乘以 1:
AVG(q.prev_transactions*1.0)? -
强制它成为一个浮点数(我来自 Transact-SQL 背景,对 Postgres 没有太多经验)
-
如果可能,请
set track_io_timing=on,然后显示EXPLAIN (ANALYZE, BUFFERS)进行查询。此外,在内部查询“q”中单独运行,并将其显示出来。
标签: sql postgresql metabase