循环遍历 Oracle PL/SQL 中的表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28387339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop through a table in Oracle PL/SQL
提问by AmericanSuave
I have done SQL queries but have not done any procedure writing that uses loops so I am at a lost here. I'm using Oracle SQL Developer. Can be done in SQL or PL/SQL
我已经完成了 SQL 查询,但没有完成任何使用循环的过程编写,所以我在这里迷路了。我正在使用 Oracle SQL Developer。可以在 SQL 或 PL/SQL 中完成
I have a table that resemble this:
我有一张类似于这样的表:
Person_ID Score Name Game_ID
1 10 Hyman 1
1 20 Hyman 2
2 15 carl 1
2 3 carl 3
4 17 steve 1
How can I loop through this table so that I can grab a players total score for all games played. Result would be like this:
我如何遍历此表,以便我可以获取所有玩过的游戏的玩家总分。结果是这样的:
Person_ID Score Name
1 30 Hyman
2 18 carl
4 17 steve
Also extra credit what If i wanted to just grab say games 1 2?
还有额外的功劳如果我只想抢说游戏 1 2?
EDIT: Sorry for not being clear but I do need to do this with a loop even though it can be done without it.
编辑:抱歉不清楚,但我确实需要用循环来做到这一点,即使没有它也可以做到。
回答by Ponder Stibbons
Solution after post edition
改版后的解决办法
This procedure list scores for given game_id. If you omit parameter all games will be summed:
此过程列出给定 game_id 的分数。如果省略参数,所有游戏都将被求和:
create or replace procedure player_scores(i_game_id number default null) as
begin
for o in (select person_id, name, sum(score) score
from games where game_id = nvl(i_game_id, game_id)
group by person_id, name)
loop
dbms_output.put_line(o.person_id||' '||o.name||' '||o.score);
end loop;
end player_scores;
Previous solution:
以前的解决方案:
You don't need procedure for that, just simple query:
你不需要过程,只是简单的查询:
select person_id, name, sum(score)
from your_table
where game_id in (1, 2)
group by person_id, name