我正在使用oracle SQL developer 11g。我有一个100名足球运动员的数据库。我有一个名为 PROFILE_PLAYERS 的表,其中包含以下列:
player_id, player_name, attack_skill(number),
defense_skill(number), passing_skill(number), GK_skill(number)
现在,我想组建一支由11名球员组成的球队,其中包括3名最佳攻击者(最高攻击技能),4名最佳中场球员(最高的pass_skill),3名最佳防守者(最佳防守技能)和1名最佳GK(最佳GK_skill)。
我想编写一个程序,用他们的player_name和player_id显示11个最佳玩家。
我可以在这里使用rank()吗?我应该在程序中使用带计数器的循环吗?
答案 0 :(得分:1)
如果您忽略由于技能不同而可以多次选择同一个玩家,则查询可能如下所示:
select player_id, player_name
from (
select player_id, player_name,
rank() over(order by attack_skill desc) attack_rank,
rank() over(order by defense_skill desc) defense_rank,
rank() over(order by passing_skill desc) passing_rank,
rank() over(order by gk_skill desc) gk_rank
from profile_players
)
where attack_rank <= 3 or defense_rank <= 4
or passing_rank <= 3 or gk_rank <= 1;
为了确保你得到11名球员,你必须申请一些技巧:
select player_id, player_name
from (
select player_id, player_name,
least((attack_rank - 1) / 3, (defense_rank - 1) / 4,
(passing_rank - 1) / 3, gk_rank - 1) blended_rank
from (
select player_id, player_name,
rank() over(order by attack_skill desc) attack_rank,
rank() over(order by defense_skill desc) defense_rank,
rank() over(order by passing_skill desc) passing_rank,
rank() over(order by gk_skill desc) gk_rank
from profile_players
)
order by blended_rank desc
)
where rownum <= 11;
如果您确实需要一个过程,则可以将此查询包装到存储过程中。