admin管理员组文章数量:1130349
在数仓开发中经常会对数据去重后统计,而对于大数据量来说,count(distinct )操作明显非常的消耗资源且性能很慢。
下面介绍我平时使用最多的一种优化方式,供大家参考。
原SQL:
select
group_id,
app_id,
count(distinct case when dt>='${7d_before}' then user_id else null end) as 7d_uv, -- 7日内UV
count(distinct case when dt>='${14d_before}' then user_id else null end) as 14d_uv --14日内UV
from tbl
where dt>='${14d_before}'
group by
group_id,
app_id
;
优化后:
先去重,再汇总。
select group_id
,app_id
,sum(case when 7d_cnt>0 then 1 else 0 end) AS 7d_uv, -- 7日内UV
,sum(case when 14d_cnt>0 then 1 else 0 end) AS 14d_uv --14日内UV
from (
select
group_id,
app_id,
user_id, --按user_id去重
count(case when dt>='${7d_before}' then user_id else null end) as 7d_cnt, -- 7日内各用户的点击量
count(case when dt>='${14d_before}' then user_id else null end) as 14d_cnt --14日内各用户的点击量
from tbl
where dt>='${14d_before}'
group by
group_id,
app_id,
user_id
) a
group by group_id,
app_id
;
希望本文对你有帮助,请点个赞鼓励一下作者吧~ 谢谢!
在数仓开发中经常会对数据去重后统计,而对于大数据量来说,count(distinct )操作明显非常的消耗资源且性能很慢。
下面介绍我平时使用最多的一种优化方式,供大家参考。
原SQL:
select
group_id,
app_id,
count(distinct case when dt>='${7d_before}' then user_id else null end) as 7d_uv, -- 7日内UV
count(distinct case when dt>='${14d_before}' then user_id else null end) as 14d_uv --14日内UV
from tbl
where dt>='${14d_before}'
group by
group_id,
app_id
;
优化后:
先去重,再汇总。
select group_id
,app_id
,sum(case when 7d_cnt>0 then 1 else 0 end) AS 7d_uv, -- 7日内UV
,sum(case when 14d_cnt>0 then 1 else 0 end) AS 14d_uv --14日内UV
from (
select
group_id,
app_id,
user_id, --按user_id去重
count(case when dt>='${7d_before}' then user_id else null end) as 7d_cnt, -- 7日内各用户的点击量
count(case when dt>='${14d_before}' then user_id else null end) as 14d_cnt --14日内各用户的点击量
from tbl
where dt>='${14d_before}'
group by
group_id,
app_id,
user_id
) a
group by group_id,
app_id
;
希望本文对你有帮助,请点个赞鼓励一下作者吧~ 谢谢!
版权声明:本文标题:别再使用count distinct了 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://it.en369.cn/jiaocheng/1754939410a2744023.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。


发表评论