有如下一组数据
求出NAME中每组累加/每组总数的比例大于0.6的ID和NAME
预期的结果应该为
解释:从题目意思可以看出A组的总数为16,从ID为1到5分别累加后的结果分别为1,3,9,13,16,只有13和16除以总数16才大于0.6,所以返回的结果ID为4和5,同样B组为7和8
select t1.id,
t1.name,
t1.num
from (
select t1.*,
sum(t1.num) over(partition by t1.name order by t1.id) /
sum(t1.num) over(partition by t1.name) per
from tab1 t1
) t1
where t1.per > 0.6
有点粗糙,期待更好的解法,
select t1.id,t1.name,t1.num
-- ,t1.s,t2.s
from (
select a.id,a.name,a.num,sum(b.num) s from tab1 a
join tab1 b
on a.id >= b.id
where a.name = 'A'
group by a.num,a.id,a.name
UNION ALL
select a.id,a.name,a.num,sum(b.num) s from tab1 a
join tab1 b
on a.id >= b.id and b.name ='B'
where a.name = 'B'
group by a.num,a.id,a.name
) t1
left join
(select name,sum(num) s from tab1 group by name ) t2
on t1.name =t2.name
where (t1.s/t2.s)>0.6
order by t1.id