count(distinct) 消耗资源过大的解决方案
前几天接到个需求,有7个字段 计算 如下:
select
stat_date
,count(distinct case when datediff(aprv_date,conf_date) = 0 then uuid else null end) as ind_1
from table_1
其中 table_1 大概有 4000万的数据量 ,7个 count(distinct 差点把服务器跑崩溃,半个小时才跑完。
以下是优化过程:
1,对table_1 做字段加工
row_number() over(partition by aprv_date,uuid order by (
case when datediff(aprv_date,conf_date) = 0 then uuid
else null end ) asc ) as ind_1
,case when datediff(aprv_date,conf_date) = 0 then 1 else 0 end
as ind_1_flag
ind_1_flag 是对 datediff(aprv_date,conf_date) = 0 条件的判断
2 ,再对 table_1 分组求和
sum( case when ind_1_flag = 1 and ind_1 = 1 then 1 else 0 end )
这样优化过后,速度会快很多,资源问题也会解决。