如何使 SQL 中同一行中每个数字的分母成为常量?

How can I make the denominator a constant for each of the numbers in the same row in SQL?

我正在尝试创建一个 table,用平均销售额除以某个月注册帐户的一组用户,但是,我只能计算除以在该特定月份进行购买的人数低于同类群组的总数。我如何更改下面的查询以使每个 avg_sucessful_transacted 金额除以每个月的同类群组 0?

谢谢。

select sum (t.amount_in_dollars)/ count (distinct u.id)  as Avg_Successful_Transacted, (datediff(month,[u.created:month],[t.createdon:month])) as Cohort, [u.created:month] as Months,
count (distinct u.id) as Users
from [transaction_cache as t]
left join [user_cache as u] on t.owner = u.id
where t.type = 'savings' and t.status = 'successful' and [u.created:year] > ['2017-01-01':date:year]
group by cohort, months
order by Cohort, Months

您需要将同类群组规模划分到它自己的子查询或 CTE 中,以便计算在与同类群组的基准月份相匹配的月份内创建的不同用户总数。

我通过使用 date_trunc('Month', <date>, <date>) 函数按创建用户的月份对用户进行分桶来解决这个问题,但您可能希望根据生成同类群组的特定业务逻辑以不同的方式处理它。

我不使用 Periscope,因此下面的示例查询是针对纯 Redshift 构建的,但希望可以轻松地将语法转换为 Periscope 的预期格式:

WITH cohort_sizes AS (
    SELECT date_trunc('Month', created)::DATE AS cohort_month
         , COUNT(DISTINCT(id)) AS cohort_size
    FROM user_cache u
    GROUP BY 1
),

cohort_transactions AS (
    SELECT date_trunc('Month', created)::DATE AS cohort_month
         , createdon
         , owner
         , type
         , status
         , amount_in_dollars
         , id
         , created
    FROM transaction_cache t
        LEFT JOIN user_cache u ON t.owner = u.id
    WHERE t.type = 'savings'
        AND t.status = 'successful'
        AND u.created > '2017-01-01'
)

SELECT SUM(t.amount_in_dollars) / s.cohort_size AS Avg_Successful_Transacted
     , (datediff(MONTH, u.created, t.createdon)) AS Cohort
     , u.created                                                 AS Months
     , count(DISTINCT u.id)                                      AS Users
FROM cohort_transactions t
    JOIN cohort_sizes s ON t.cohort_month = s.cohort_month
    LEFT JOIN user_cache AS u ON t.owner = u.id
GROUP BY s.cohort_size, Cohort, Months
ORDER BY Cohort, Months
;