我试图找出如何编写一个查询,以获取在过去12个月中活跃的用户,在2017年的某个月,然后在一个月内进行交易。
示例:
2017年12月,谁进行了交易,这是2016年12月至2017年12月交易的每个人的比例
我遇到的问题是我还需要按产品和国家/地区对这些用户进行分组
这是我的一行:
客户ID | transaction_date |接收国|产品买了|交易ID
我尝试过几种方法:
WITH transacting_dec_users AS (
SELECT
user_id AS transactor,
COUNT(*) AS transactions
FROM database
WHERE transaction_date >= '2017-12-01'
GROUP BY user_id),
dec_actives AS (
SELECT
user_id,
transactions,
COUNT(*) AS active_in_12_months,
product,
receive_country,
sender_country
FROM database t1
LEFT OUTER JOIN transacting_users t2 ON t2.transactor = t1.user_id
WHERE transaction_date >= '2016-12-01'
GROUP BY 1,2,4,5,6)
SELECT
SUM(CASE WHEN transactions IS NULL THEN 1 ELSE 0 END) AS actives_not_transact,
SUM(CASE WHEN transactions IS NOT NULL THEN 1 ELSE 0 END) AS transactor
FROM actives
我确实尝试过子查询,但我不能让他们使用我的分组,因为我需要将每个客户分组到国家/地区和产品中
我理想的结果是:
答案 0 :(得分:0)
我对您期望结果的解释:对于每个(月,服务,receiver_country)计算交易的用户数量,并计算在该月的一年内交易的用户数量。这个查询应该可以解决问题(它未经测试,因此可能会有一些修复)。
; with
TransactedThisMonth as (
select date_trunc('month', transaction_date) as month
, service
, receiver_country
, count(distinct user_id) as transacting_users
from table_name
group by date_trunc('month', transaction_date)
, service
, receiver_country
)
select a.*, sum(b.transacting_users) as actives
from TransactedThisMonth a
left join TransactedThisMonth b
on b.service = a.service
and b.reciever_country = a.receiver_country
and b.month between a.month - interval '1 year' and a.month
group by a.month
, a.service
, a.receiver_country
, a.transacting_users