我有一张桌子(
wallet_credit_details
)其中每一行是由单个客户进行的单个交易。还有一张桌子(
wallet_usage_details
)其显示了每个用户如何为这些交易付费。我想做的是,对于第一个表中的每一行(交易),将客户从第二个表到第一个表的交易日期的值进行聚合(计数和求和)。
一个例子是,对于每笔交易,计算我们使用“充值”支付的同一客户之前的交易次数。
SELECT
wallet.customer_id,
wallet.credit_id AS transaction_id,
COALESCE(COUNT(usage.debit_id), 0) AS transactions_paid_count_to_date,
COALESCE(SUM(usage.used_amt_usd), 0) AS transactions_paid_amount_to_date,
COALESCE(COUNT(CASE WHEN usage.credit_title = 'Topups' AND usage.credit_type = 'Credit Card Topups' THEN 1 END), 0) AS topups_used_count_to_date,
COALESCE(SUM(CASE WHEN usage.credit_title = 'Topups' AND usage.credit_type = 'Credit Card Topups' THEN usage.used_amt_usd END), 0) AS topups_used_amount_to_date
FROM
prod_dwh.wallet_credit_details AS wallet
LEFT JOIN
prod_dwh.wallet_usage_details AS usage
ON
wallet.customer_id = usage.user_id
AND usage.transaction_date < wallet.day
WHERE
wallet.credit_title = 'Topups'
AND wallet.credit_type = 'Credit Card Topups'
AND wallet.day >= DATE '{min_date}'
AND wallet.day <= DATE '{max_date}'
GROUP BY
wallet.customer_id,
wallet.credit_id
如何使用窗口函数再现相同的逻辑?