문제

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