首页 > 解决方案 > 我有一个通话数据表我想计算每天调用的唯一帐户的数量,并按月计算唯一帐户的总和

问题描述

我有一个有 2 个唯一列的表,一个有一个帐号,另一个是日期。样本数据如下。

Date    account
9/8/2020    555
9/8/2020    666
9/8/2020    777
9/8/2020    888
9/9/2020    555
9/9/2020    999
9/10/2020   555
9/10/2020   222
9/10/2020   333
9/11/2020   666
9/11/2020   111

我想计算每天调用的唯一帐户的数量并将其总结为一个月,例如,如果在 8 月 8 日、9 月 9 日和 9 月 20 日调用了 555 号帐户,则它的总和不等于累积总和,结果应该看起来像这个

date    Cumulative Unique Accounts Called SO Far this month
9/8/2020    4
9/9/2020    5
9/10/2020   7
9/11/2020   8

预先感谢您的帮助。

标签: sqlsql-server

解决方案


您可以使用聚合和窗口函数来做到这一点。首先,获取每个账户的第一个日期,然后聚合并累加:

select min_date,
       count(*) as as_of_date,
       sum(count(*)) over (partition by year(min_datedate), month(min_datedate)
                           order by min_date
                          ) as cumulative_unique_count
from (select account, min(date) as min_date
      from t
      group by account, year(date), month(date)
     ) t
group by min_date;

推荐阅读