问题描述
我有一个配置单元表,该配置单元根据数字值(例如count)进行了排序。
fruit count
------ -------
apple 10
orange 8
banana 5
melon 3
pears 1
总数为27。我需要将其分为三个部分。因此,计数的前1/3,即1到9是1,10到18是第二,而19到27是第三。 我想我需要做一些滑动窗口的事情。
fruit count zone
------ ------- --------
apple 10 one
orange 8 two
banana 5 three
melon 3 three
pears 1 three
任何想法如何解决这个问题
解决方法
以SQL方式:
select *,(
sum(count) over (partition by 1 order by count desc) /*<---this line for return running totals*/
/(sum(count) over (partition by 1) /3) /*<-- divided total count into 3 group. In your case this is 9 for each zone value.*/
) /*<--using running totals divided by zone value*/
+ /*<-- 11 / 9 = 1 ... 2 You must plus 1 with quotient to let 11 in the right zone.Thus,I use this + operator */
(
case when
(
sum(count) over (partition by 1 order by count desc)
%(sum(count) over (partition by 1) /3) /*<--calculate remainder */
) >1 then 1 else 0 end /*<--if remainder>1 then the zone must +1*/
) as zone
from yourtable