我正在尝试在 this tutorial 之后使用 PostgreSQL 9.5.2 实现计算用户保留和流失的查询
我有一个事件表定义为:
CREATE TABLE public.messages
(
id character(100) NOT NULL,
"userId" character(100),
"createdAt" timestamp without time zone,
CONSTRAINT messages_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
计算保留的用户工作得很好,但我在运行此查询时遇到计算为 null 的“userId”的问题:
with monthly_activity as (
select distinct
date_trunc('month', "createdAt") as month,
"userId"
from messages
)
select
this_month.month,
count(distinct this_month."userId")
from monthly_activity last_month
left join monthly_activity this_month
on this_month."userId" = last_month."userId"
and this_month.month = last_month.month + interval '1 month'
where this_month."userId" is null
group by 1
表正在正确连接,但计算空值似乎没有返回任何结果。
关于如何让它工作的任何提示?
谢谢!
最佳答案
COUNT
函数忽略空值。您的 where 子句设置为专门确保 this_month."userId"
始终为 null。
改为将查询更改为 count(distinct last_month."userId")
。
计数文档:http://www.postgresql.org/docs/current/static/functions-aggregate.html
关于sql - 使用 Postgresql 计算用户流失率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37253108/