views:

35

answers:

2

users table:

id-user-other columns

scores table:

id-user_id-score-other columns

They're are more than one rows for each user, but there's only two scores you can have. (0 or 1, == win or loss). So I want to output all the users ordered by the number of wins, and all the users ordered by the numbers of losses.

I know how to do this by looping through each user, but I was wondering how to do it with one query. Any help is appreciated!

A: 

Try something like this:

SELECT u.user, 
       COALESCE(SUM(s.score), 0) AS WINS,
       SUM(CASE WHEN s.score = 0 THEN 1 ELSE s.score END) AS LOSSES 
  FROM users u
       LEFT JOIN scores s
       ON u.id = s.user_id
GROUP BY u.user
ORDER BY WINS, LOSSES
Adam Bernier
I'll try that. Although, I meant one query for the winners and losers, not one for both. Sorry. =/. They'll be going on separate pages. :-p. I'll try to modify that query, though, I guess. :-p.
Andrew
Good answer Adam, just a few quick problems...If he needs sum of wins, you dont left join. If you do you could have nulls which can cause mathematical problems. Als, since the case statement is not encapsulated in a sum it will return one row per loss per user.
TerrorAustralis
@Dave: gah, thanks. Wrote in a hurry. Fixed now.
Adam Bernier
No problem, make that mistake all the time at work... went out to lunch and came back to 231 million rows and no memory left on my computer...
TerrorAustralis
Haha, and perhaps an email from the not-so-elated DBA ;-) Thanks for the corrections.
Adam Bernier
+4  A: 

if you want two outputs you need two queries

SELECT u.user,
COUNT(s.score) as WINS
FROM users u INNER JOIN scores s
     ON u.user_id = s.user_id 
WHERE s.score = 1
GROUP BY u.user_id (and any other columns you need from the user table)
ORDER BY WINS

You then do another query for the losses.
Essentially this is the same as Adams response, but his response will give you a list of users ordered by wins, then ordered by losses. To get losses, just change the s.score=1 to s.score = 0

TerrorAustralis
+1 because you figured out what the OP wanted unlike me :-)
Adam Bernier
Thanks, this was what I needed. (I wish I could accept both answers! Sorry!)
Andrew