I have a table called bets. I want to return records based on the distinct values of multiple columns and then perform an aggregate query on that record set. This query doesn't work, of course, but should illustrate what I'm trying to do:

Bet.select('distinct user_id, event_id, bet_line_id, state, pick').
select("user_id, COUNT(CASE WHEN state = 'won' then 1 ELSE null END) 
AS bets_won, COUNT(CASE WHEN state = 'lost' then 1 ELSE null END) 
AS bets_lost, COUNT(CASE WHEN state = 'pushed' then 1 ELSE null END) 
AS bets_pushed").group('user_id')

If it's unclear what I'm asking, I'll provide a more illustrative example.

Using Rails 3.2 and postgres, btw.

有帮助吗?

解决方案

I'm sure there are other ways, but I would tackle this with a Common Table Expression. You can write the SQL by hand or take a look at the postgres_ext gem: https://github.com/dockyard/postgres_ext/blob/master/docs/querying.md

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top