sql - 我如何计算一个月内不在前一个月的用户数?

标签 sql google-bigquery psql

我正在尝试按月计算上个月不存在的唯一用户数。因此,如果一个用户有 1 月的记录,然后有 2 月的另一个记录,那么我只会为该用户计算 1 月。

user_id    time
a1         1/2/17
a1         2/10/17
a2         2/18/17
a4         2/5/17
a5         3/25/17

我的结果应该是这样的

Month   User Count
January     1
February    2
March       1

最佳答案

我对 BigQuery 不是很熟悉,但下面是我使用 TSQL 解决问题的方法。我想您将能够在 BigQuery 中使用类似的逻辑。

1).先按user_id对数据排序,再按时间排序。在 TSQL 中,您可以使用以下内容完成此操作并将其存储在一个公共(public)表表达式中,您将在这之后的步骤中查询。

;WITH cte AS
(
select  ROW_NUMBER() OVER (PARTITION BY [user_id] ORDER BY [time]) AS rn,*
from    dbo.employees
)

2). Next 仅查询 rn = 1 的行(特定用户第一次出现)并按月分组。

select    DATENAME(month, [time]) AS [Month], count(*) AS user_count 
from      cte
where     rn = 1    
group by  DATENAME(month, [time])

这是假设 2017 年是您要处理的唯一一年。如果您处理的时间超过一年,您可能希望第 2 步看起来像这样:

select    year([time]) as [year],  DATENAME(month, [time]) AS [month], 
          count(*) AS user_count 
from      cte
where     rn = 1    
group by  year([time]), DATENAME(month, [time])

关于sql - 我如何计算一个月内不在前一个月的用户数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43420085/

相关文章:

mysql - 使用 LIMIT 子句进行计数

google-bigquery - 如何计算bigquery行大小?

PostgreSQL:使用不带斜杠语法的 SQL 显示域属性

mysql - Mysql - 从数据库日期创建分组数据列表

php - SQL:使用计数查询返回 1

google-analytics - 为何在BigQuery中(但在Google Analytics(分析)中没有带有小时一分钟的浏览量条目)?

postgresql - psql 列出所有表

postgresql - 删除用户后尝试访问 psql 但仍被要求输入已删除用户的密码

mysql - 在mysql中创建复合索引

google-bigquery - 创建公共(public)数据集(或 : split storage costs and compute costs across two projects)