我有一个简单的表:user(id, date, task)
任务字段包含“下载”或“上传”
我想算出每天执行每个操作的用户数量。
输出:日期,下载的用户数量,上传的用户数量
我首先遇到了在select的聚合计数函数中使用子查询的问题,所以我认为我应该在这里使用自连接来分解“任务”列中的数据。
我以为我可以为每个案例创建表格,然后将它们组合起来并进行计数,但我无法完成它:
SELECT id, date, task as task_download FROM user WHERE task = 'download'
SELECT id, date, task as task_upload FROM user WHERE task = 'upload'
我会说,既不是也不是。只需像这样的查询就可以完成这项工作:
select `date`,
count(distinct case when task = 'download' then id else null end) as downloads,
count(distinct case when task = 'upload' then id else null end) as uploads
from user
where task in ('download', 'upload')
group by `date`
假设,date
是一个只包含日期部分而不是完整时间戳的列,并且id
是用户 ID。您可以distinct
在聚合函数中使用关键字,这就是我在这里所做的。
为了让这个查询运行得足够快,我建议在 task,date
但是,如果date
包含完整的时间戳(即包括时间部分),您可能希望以不同的方式分组:
select `date`,
count(distinct case when task = 'download' then id else null end) as downloads,
count(distinct case when task = 'upload' then id else null end) as uploads
from user
where task in ('download', 'upload')
group by date(`date`)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句