要在PostgreSQL中计算每月事务处理用户占滚动12个月期间用户的比例,并且具有分组功能,可以使用窗口函数和CTE(Common Table Expressions)。以下是一个示例查询,假设你有一个名为transactions
的表,其中包含user_id
和transaction_date
字段。
WITH monthly_users AS (
SELECT
DATE_TRUNC('month', transaction_date) AS month,
user_id
FROM
transactions
GROUP BY
DATE_TRUNC('month', transaction_date),
user_id
),
rolling_12_month_users AS (
SELECT
month,
user_id
FROM
monthly_users
WHERE
month >= CURRENT_DATE - INTERVAL '11 month'
GROUP BY
user_id
HAVING
COUNT(DISTINCT DATE_TRUNC('month', transaction_date)) = 12
),
monthly_active_users AS (
SELECT
DATE_TRUNC('month', transaction_date) AS month,
COUNT(DISTINCT user_id) AS active_users
FROM
transactions
WHERE
transaction_date >= CURRENT_DATE - INTERVAL '11 month'
GROUP BY
DATE_TRUNC('month', transaction_date)
),
monthly_total_users AS (
SELECT
month,
COUNT(DISTINCT user_id) AS total_users
FROM
rolling_12_month_users
GROUP BY
month
)
SELECT
ma.month,
ma.active_users,
mt.total_users,
(ma.active_users::float / mt.total_users::float) * 100 AS percentage
FROM
monthly_active_users ma
JOIN
monthly_total_users mt
ON
ma.month = mt.month
ORDER BY
ma.month;
monthly_active_users
和monthly_total_users
连接起来,并计算每个月活跃用户占总用户的百分比。如果你需要按某个字段(例如category
)进行分组,可以在每个CTE中添加相应的GROUP BY
子句,并在最终查询中进行相应的调整。
例如,如果你的transactions
表有一个category
字段,你可以这样修改查询:
WITH monthly_users AS (
SELECT
DATE_TRUNC('month', transaction_date) AS month,
category,
user_id
FROM
transactions
GROUP BY
DATE_TRUNC('month', transaction_date),
category,
user_id
),
rolling_12_month_users AS (
SELECT
month,
category,
user_id
FROM
monthly_users
WHERE
month >= CURRENT_DATE - INTERVAL '11 month'
GROUP BY
category,
user_id
HAVING
COUNT(DISTINCT DATE_TRUNC('month', transaction_date)) = 12
),
monthly_active_users AS (
SELECT
DATE_TRUNC('month', transaction_date) AS month,
category,
COUNT(DISTINCT user_id) AS active_users
FROM
transactions
WHERE
transaction_date >= CURRENT_DATE - INTERVAL '11 month'
GROUP BY
DATE_TRUNC('month', transaction_date),
category
),
monthly_total_users AS (
SELECT
month,
category,
COUNT(DISTINCT user_id) AS total_users
FROM
rolling_12_month_users
GROUP BY
month,
category
)
SELECT
ma.month,
ma.category,
ma.active_users,
mt.total_users,
(ma.active_users::float / mt.total_users::float) * 100 AS percentage
FROM
monthly_active_users ma
JOIN
monthly_total_users mt
ON
ma.month = mt.month AND ma.category = mt.category
ORDER BY
ma.month, ma.category;
这样,你就可以按月份和类别计算每月事务处理用户占滚动12个月期间用户的比例。
领取专属 10元无门槛券
手把手带您无忧上云