sql - 使用 Postgresql 计算用户流失率

标签 sql postgresql join metrics

我正在尝试在 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/

相关文章:

sql - 连接表时如何显示未使用的外键值

postgresql - mix ecto.create 失败 (** (Postgrex.Error) FATAL 28000 (invalid_authorization_specation) 用户“postgres”的身份验证失败

postgresql - 如何在 PostgreSQL 中设置全文搜索查询

Mysql嵌套选择与多个连接条件连接表

mysql - 如果两个表具有特定的相等性,如何进行选择连接

MySQL #1241 - 操作数应包含 1 列

MySQL - 从 2 个表中选择结果中的几列应基于条件语句

基于值的 Mysql 名称

sql - MySQL比较来自同一列的计数

sql - 在一系列 GPS 数据中寻找最近的经过点