Prev | Current Page 57 | Next

David Berube

"Practical Reporting with Ruby and Rails"


Dissecting the Code
First, the script in Listing 2-3 connects to the database and sets up the models, as you??™ve
seen in previous examples. Essentially, the remainder of the script runs two SQL statements
and prints out the results in a nice format.
The first SQL statement returns the overall results for all games combined. To retrieve
that result, the query groups by the drink field, and then uses a correlated subquery to
retrieve the total number of wins:
sql = "SELECT drink,
COUNT(*) as total_players,
(SELECT SUM(quantity) FROM wins
WHERE wins.player_id=players.id) as total_wins
CHAPTER 2 n CALCULATING STATISTICS WITH ACTIVE RECORD 30
FROM players
GROUP
BY players.drink
;"
The grouping ensures that the main statement produces one row per drink. The
correlated subquery produces a sum for each of those rows by looping through the wins
table and totaling all of a player??™s wins. The code then proceeds to loop through the
results and print them out.
Next, the second query produces a result specific to each game:
sql = "SELECT drink,
games.


Pages:
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69