擺弄這個鏈接。
我有一個包含 user_id 和 action_time 的表: Schema (PostgreSQL v13)
CREATE TABLE actions(
action_time timestamp,
user_id int
);
insert into actions values ('2015-01-20 01:00',1);
insert into actions values ('2015-01-01 01:00',1);
insert into actions values ('2015-01-10 01:00',1);
insert into actions values ('2015-01-12 01:00',1);
insert into actions values ('2015-01-16 01:00',1);
insert into actions values ('2015-01-23 01:00',1);
insert into actions values ('2015-02-20 01:00',1);
insert into actions values ('2015-03-20 01:00',1);
insert into actions values ('2015-05-20 01:00',1);
insert into actions values ('2015-06-20 01:00',1);
insert into actions values ('2015-01-20 01:00',2);
insert into actions values ('2015-03-20 01:00',2);
insert into actions values ('2015-04-20 01:00',2);
insert into actions values ('2015-05-20 01:00',2);
insert into actions values ('2015-05-21 01:00',2);
insert into actions values ('2015-05-21 01:00',2);
insert into actions values ('2015-05-23 01:00',2);
我想檢查用戶是否在 6 個月內每個月至少執行過一次操作。
通過使用它,我可以獲得用戶每個月完成的運算元:
SELECT date_trunc('month',action_time) AS month_parth, user_id,COUNT(*) AS
monthly_actions FROM actions
GROUP BY month_parth,user_id
ORDER BY user_id,month_parth ASC;
并獲得以下內容:
查詢#1
SELECT date_trunc('month',action_time) AS month_parth, user_id,COUNT(*) AS monthly_actions FROM actions
GROUP BY month_parth,user_id
ORDER BY user_id,month_parth ASC;
| 月份_parth | 用戶身份 | 每月_動作 |
|---|---|---|
| 2015-01-01T00:00:00.000Z | 1 | 6 |
| 2015-02-01T00:00:00.000Z | 1 | 1 |
| 2015-03-01T00:00:00.000Z | 1 | 1 |
| 2015-05-01T00:00:00.000Z | 1 | 1 |
| 2015-06-01T00:00:00.000Z | 1 | 1 |
| 2015-01-01T00:00:00.000Z | 2 | 1 |
| 2015-03-01T00:00:00.000Z | 2 | 1 |
| 2015-04-01T00:00:00.000Z | 2 | 1 |
| 2015-05-01T00:00:00.000Z | 2 | 4 |
user_id 1 顯然每月至少有一次操作(在 1 月的 6 時達到峰值),但 2 有一些差距。
我不知道如何去這里,如果我需要做一個新的查詢分組和使用 HAVING 或者如何下一步。
對于在 6 個月內每月至少執行一次操作的用戶,所需的結果可能是一個簡單的虛擬列,其中包含 TRUE/FALSE。
uj5u.com熱心網友回復:
這是一個查詢,其中one_action_per_month_during_next_6_months是每個 user_id 和每個月的布林值,如果用戶在接下來的幾個月中至少執行了一個操作,則為 true:
WITH list AS
(
SELECT date_trunc('month',action_time) AS month_parth
, user_id, COUNT(*) AS monthly_actions
FROM actions
GROUP BY month_parth,user_id
)
SELECT user_id
, month_parth
, monthly_actions
, count(*) FILTER (WHERE monthly_actions >=1) OVER (PARTITION BY user_id ORDER BY month_parth RANGE BETWEEN CURRENT ROW AND '6 months' FOLLOWING) = 6 AS one_action_per_month_during_next_6_months
FROM list AS l
ORDER BY user_id,month_parth ASC
dbfiddle 中的測驗結果
uj5u.com熱心網友回復:
select user_id, count(cnt) >= 6 six_months from
(
select user_id, date_trunc('month', action_time) monthperiod, count(*) cnt
from actions
group by user_id, monthperiod
) t
group by user_id;
順便說一句,用戶 1 沒有 6 個月的時間進行至少一項操作,因為他缺少四月。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380149.html
標籤:PostgreSQL的
