我喜欢编写一个sql查询来计算每个用户使用该应用程序的天数以及多少个并发天数。用户可以每天多次输入应用,但应该计为1。
我的表格如下:
id | bigint
user_id | bigint
action_date | timestamp without time zone
答案 0 :(得分:1)
计算每位用户的天数:
SELECT user_id, count(DISTINCT action_date::date) AS days
FROM user_action_tbl
GROUP BY user_id;
答案 1 :(得分:0)
一种方法
SELECT user_id, COUNT(*) days_total, SUM(conseq) days_consecutive
FROM
(
SELECT user_id,
CASE WHEN LEAD(date, 1) OVER (PARTITION BY user_id ORDER BY date) - date = 1 THEN 1 ELSE 0 END consecutive
FROM
(
SELECT user_id, action_date::date date
FROM table1
GROUP BY user_id, action_date::date
) q
) p
GROUP BY user_id
这是 SQLFiddle 演示