Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a table in Oracle PL/SQL

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

I have a table that resemble this:

Person_ID Score Name  Game_ID
1         10    jack  1
1         20    jack  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    jack
2         18    carl
4         17    steve

Also extra credit what If i wanted to just grab say games 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.

like image 445
AmericanSuave Avatar asked Feb 07 '15 21:02

AmericanSuave


1 Answers

Solution after post edition

This procedure list scores for given game_id. If you omit parameter all games will be summed:

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
like image 155
Ponder Stibbons Avatar answered Sep 20 '22 17:09

Ponder Stibbons