我正在进行一些队列分析,并希望在11月看到一组客户,每周,每两周和每月进行多少次交易;和多长时间
我有这个周和月(每周例子):
WITH weekly_users AS (
SELECT user_fk
, DATE_TRUNC('week',created_at) AS week
, (DATE_PART('year', created_at) - 2016) * 52 + DATE_PART('week', created_at) - 45 AS weeks_between
FROM transactions
WHERE created_at >= '2016-11-01' AND created_at < '2017-12-01'
GROUP BY user_fk, week, weeks_between
),
t2 AS (
SELECT weekly_users.*
, COUNT(*) OVER (PARTITION BY user_fk
ORDER BY week ROWS BETWEEN UNBOUNDED PRECEDING
AND 1 PRECEDING) AS prev_rec_cnt
FROM weekly_users
)
SELECT week
, COUNT(*)
FROM t2
WHERE weeks_between = prev_rec_cnt
GROUP BY week
ORDER BY week;
但每周间隔时间太少,而且每月太多。所以我想要两个星期。有没有人这样做过?从谷歌搜索似乎是一个挑战
提前致谢
答案 0 :(得分:1)
刚刚解决了,这就是你要做的事情:
WITH fortnightly_users AS (
SELECT user_fk
, EXTRACT(YEAR FROM created_at) * 100 + CEIL(EXTRACT(WEEK FROM created_at)/2) AS fortnight
, (EXTRACT(YEAR FROM created_at) - 2016) * 26 + CEIL(EXTRACT(WEEK FROM created_at)/2) - 23 AS fortnights_between
FROM transactions
WHERE created_at >= '2016-11-01' AND created_at < '2017-12-01'
GROUP BY user_fk, fortnight, fortnights_between
),
t2 AS (
SELECT fortnightly_users.*
, COUNT(*) OVER (PARTITION BY user_fk
ORDER BY fortnight ROWS BETWEEN UNBOUNDED PRECEDING
AND 1 PRECEDING) AS prev_rec_cnt
FROM fortnightly_users
)
SELECT fortnight
, COUNT(*)
FROM t2
WHERE fortnights_between = prev_rec_cnt
GROUP BY fortnight
ORDER BY fortnight;
所以你得到周数,然后除以2.四舍五入以避免四分之一的分数