每月交易用户占滚动12个月期间的比例,但与分组 - Postgres

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

我正在尝试研究如何编写一个查询,以获取在过去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

我确实尝试过子查询,但我不能让他们与我的分组一起工作,因为我需要将每个客户分组到各个国家和产品中

我理想的结果是:

enter image description here

sql postgresql join presto
1个回答
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 
© www.soinside.com 2019 - 2024. All rights reserved.