如何在 SQL Percentile Window 函数上添加条件?
How to add Conditions on SQL Percentile Window function?
我想做一个特殊的查询来评估团队成员。每个成员都会有一个分数,分数大于该团队分数的 80% 的成员将获得奖金。但是,我想添加一个条件,以便仅根据那些 > 0 的分数计算第 80 个百分位分数。
例如,如果 A 队有
[0, 0, 0.6, 0.6, 0.8, 0.8]
然后将使用
计算百分位数
[0.6, 0.6, 0.8, 0.8]
结果将是 0.8。否则,如果团队只有分数 = 0,则 team_80th_score 将为 0。
table 看起来像这样,team_80th_score* 是想要的结果。
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
我使用 Hive SQL,并且了解在这个基础 window 功能的基础上构建将是可行的方法
select team, member, score,
percentile_approx(score, 0.8) over (partition by team) as team_80th_score
from table;
但我不知道如何包含只考虑分数 > 0 的条件(对于像 A 队这样的情况),如果 sum(score) group by team 是 0 那么 0 end as team_80th_score(对于 B 队这样的案例)。
在这种情况下你会推荐我做什么?
嗯嗯。 . .一种方法是在 partition by
中包含逻辑。请注意,当 score = 0
:
时,此 returns 无意义值
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;
我想做一个特殊的查询来评估团队成员。每个成员都会有一个分数,分数大于该团队分数的 80% 的成员将获得奖金。但是,我想添加一个条件,以便仅根据那些 > 0 的分数计算第 80 个百分位分数。
例如,如果 A 队有
[0, 0, 0.6, 0.6, 0.8, 0.8]
然后将使用
计算百分位数[0.6, 0.6, 0.8, 0.8]
结果将是 0.8。否则,如果团队只有分数 = 0,则 team_80th_score 将为 0。
table 看起来像这样,team_80th_score* 是想要的结果。
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
我使用 Hive SQL,并且了解在这个基础 window 功能的基础上构建将是可行的方法
select team, member, score,
percentile_approx(score, 0.8) over (partition by team) as team_80th_score
from table;
但我不知道如何包含只考虑分数 > 0 的条件(对于像 A 队这样的情况),如果 sum(score) group by team 是 0 那么 0 end as team_80th_score(对于 B 队这样的案例)。
在这种情况下你会推荐我做什么?
嗯嗯。 . .一种方法是在 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;