我有一个如下所示的 postgres 表:
id | user_id | state | created_at
状态可以是以下任何一种:
new, paying, paid, completing, complete, payment_failed, completion_failed
我需要一个返回报告的语句,其中包含以下内容:
- 按日期计算的所有已付款状态的总和
- 按日期列出的所有已完成状态的总和
- 按日期计算的所有新的、付费的、完成状态的总和,每个用户每天只计算一个
- 按日期计算的所有 payment_failed、completion_failed 的总和,每个用户每天只计算一个
到目前为止,我有这个:
SELECT
DATE(created_at) AS date,
SUM(CASE WHEN state = 'complete' THEN 1 ELSE 0 END) AS complete,
SUM(CASE WHEN state = 'paid' THEN 1 ELSE 0 END) AS paid
FROM orders
WHERE created_at BETWEEN ? AND ?
GROUP BY DATE(created_at)
通过将其添加到选择中,进行中和失败状态的总和很容易:
SUM(CASE WHEN state IN('new','paying','completing') THEN 1 ELSE 0 END) AS in_progress,
SUM(CASE WHEN state IN('payment_failed','completion_failed') THEN 1 ELSE 0 END) AS failed
但是我无法弄清楚如何每天只为每个 user_id 制作一个 in_progress 和失败的状态来计算。
The reason I need this is to manipulate the failure rate in our stats, as many users who trigger a failure or incomplete order go on to trigger more which inflates our failure rate.
Thanking you in advance.