sql - 我有一个通话数据表我想计算每天调用的唯一帐户的数量,并按月计算唯一帐户的总和
问题描述
我有一个有 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
预先感谢您的帮助。
解决方案
您可以使用聚合和窗口函数来做到这一点。首先,获取每个账户的第一个日期,然后聚合并累加:
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;
推荐阅读
- javascript - 在 AWS lambda 函数中使用个人需求的优势
- python-3.x - Pytest 在某个线程中运行某个测试套件
- android - Android Studio - Android 模拟器以不同的方式呈现布局。模拟器运行程序时高度似乎较小
- ios - Apple TV 第 4 代中的 Powerpoint
- java - 根据长度乘以数字
- ios - 单击图像时如何添加操作?
- c# - 如何将 Localhost(网站)连接到 UWP 应用程序?
- sql - 评估多个列并返回与值条件匹配的列的 SQL 案例语句?
- python - 从 Python 获取参数的类中调用方法具有意外类型
- c# - 在 VFP 中完成 dll 的 WCF 中的 com 引用出错