如何在sql百分位窗口函数上添加条件?

w7t8yxp5  于 2021-06-27  发布在  Hive
关注(0)|答案(1)|浏览(582)

我想做一个特殊的查询来评估团队成员。每个成员都有一个得分,得分超过该队得分80%的人将获得奖金。但是,我想添加一个条件,使第80个百分位数的分数仅基于那些大于0的分数计算。
例如,如果团队a

[0, 0, 0.6, 0.6, 0.8, 0.8]

然后将使用

[0.6, 0.6, 0.8, 0.8]

结果是0.8。否则,如果团队只有分数=0,那么团队第80个分数将为0。
表格如下所示,第80个队的得分*是期望的结果。

team| member | score | team_80th_score*
----+-----------+------+--------
A   | Alex   |  0    |     0.8 
A   | Abby   |  0    |     0.8   
A   | Hunt   |  0.6  |     0.8  
A   | Tyler  |  0.6  |     0.8 
A   | Jack   |  0.8  |     0.8 
A   | Mile   |  0.8  |     0.8 
B   | John   |  0    |     0 
B   | Amy    |  0    |     0 
B   | Alice  |  0    |     0

我使用hivesql,并且理解在这个基本窗口函数的基础上进行构建将是一种可行的方法

select team, member, score, 
percentile_approx(score, 0.8) over (partition by team) as team_80th_score
from table;

但我不知道如何包含只考虑得分>0的条件(对于像a队这样的情况),如果一组一组的总和(得分)为0,那么0结束为第80个团队的得分(对于像b队这样的情况)。
在这种情况下你建议我怎么办?

uidvcgyl

uidvcgyl1#

嗯。一种方法是将逻辑包含在 partition by . 注意,当 score = 0 :

select team, member, score, 
       percentile_approx(score, 0.8) over (partition by team, (case when score > 0 then 1 else 0 end) as team_80th_score
from table;

要解决这个问题,用一个外罩 case 表达式:

select team, member, score, 
       (case when score > 0
             then percentile_approx(score, 0.8) over (partition by team, (case when score > 0 then 1 else 0 end))
        end) as team_80th_score
from table;

相关问题