Prev | Current Page 58 | Next

David Berube

"Practical Reporting with Ruby and Rails"

name as game,
COUNT(*) as total_players,
(SELECT SUM(quantity) FROM wins
WHERE wins.player_id=players.id
AND wins.game_id=games.id) as total_wins
FROM players,
games
GROUP
BY games.name,
players.drink
; "
This uses a cross join and grouping. In other words, it produces one row for every
combination of game and drink. For each of those rows, the subquery totals all wins that
refer to the current game and to players who drink the current drink.
Once you have this query, it??™s reasonably trivial to print out the results.
Summary
Reporting often involves arduous statistical calculations. When you write code to performthese
calculations by hand, you??™re reinventing the wheel??”writing code that has
been written countless times before. It??™s also easy to write slow code when you create it
CHAPTER 2 n CALCULATING STATISTICS WITH ACTIVE RECORD 31
by hand. Fortunately, database systems contain fast, easy-to-use methods to create blazingly
quick queries, and Active Record can make creating those queries even easier.


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