views:

19

answers:

1

Is there a way I can query the database to return only the elements that have happened successively (in time) according to a set variable?

Specifically, I need to find out how many times the user has won a game in a row. The games are stored in the database with an attribute win_loss (1 is win, 0 is loss).

I would like to see if the user has won 3 games in a row. Is there a way to do this in the database?

If not, what would it look like in the application?

I apologize ahead of time if this is confusing. Please ask questions and I will try to clear it up. I'm using Ruby on Rails.

+2  A: 

I would take different approach. I would add a column consecutive_wins into your User model (negative numbers could represent consecutive losses if you need that as well).

EDIT: if you really need to query it...

Two queries:

  1. select the newest victory and newest loose for given user (could be done in one query, in SQL SELECT max(created_at) AS newest, win_loss FROM games GROUP BY win_loss (I can't recall how to do grouping functions in Rails right now but you should get the idea)
  2. and then, regarding the result of query (1):
    1. if both newest win and newest lose are found, count the games with condition that created_at > newest_win AND created_at > newest_lose
    2. if only newest win or lose found, user was always wining or always loosing, just count the number of his games
    3. in other case there were no games

I recommend adding the column to user model, it will be better when you need to display the whole table of gamers and their consecutive wins/loses.

skalee
Say I add the consecutive wins/losses to my User model. How would you go about finding it that way?
jfedick
Sorry, I don't understand your question... What do you want to find?
skalee
Well, even if I add the column consecutive_wins to my User model, I still need to find the consecutive wins and input it into the table. How would you suggest doing that?
jfedick
You don't need to. Any time the user finishes his game, you are updating this column according to its previous value. If he wins and the consecutive_wins_loses is positive, you are increasing its value by one. If he wins and the consecutive_wins_loses is negative or equal to zero, you are setting it to -1. For loses, you do similar thing.
skalee
That works. Thanks for the idea!
jfedick