0

I have 2 tables "quizzes" & "users", I need to return list of first user took each quiz, with quiz_id:

tables structure

"quizzes" structure:
id     name
1     England
2     france
3     Japan
4     USA
5     UAE
6     Sweden
7     Italy
8     Brazil
9     South Korea
10    India


"users" structure:
id    user_id     quiz_id
1       1            1
2       1            2
3       2            1
4       3            4
5       1            4
6       5            9
7       2            9
8       3            8
9       3            9
10      3            7

I need to run query to return first "user_id" took each "quiz", (order by users.id ASC)

expected results:
quiz_id     user_id
   1           1
   2           1
   4           3
   7           3
   8           3
   9           5

thanks,

mwafi
  • 3,946
  • 8
  • 56
  • 83
  • 1
    Join on a subqery with MIN(user_id).... GROUP BY quiz_id – Mihai Jun 14 '15 at 12:29
  • @Mihai pls, can u provide full query? – mwafi Jun 14 '15 at 12:30
  • This is a classic [greatest-n-per-group](http://stackoverflow.com/questions/7745609/sql-select-only-rows-with-max-value-on-a-column) (or least, in this case) problem, of which there are many existing solutions. – Clockwork-Muse Jun 14 '15 at 13:28

2 Answers2

1

You first group by quiz and pick minimal id and then select based on those ids:

select quiz_id, user_id
from users 
where id in(select min(id) from users group by quiz_id)
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
0
Select quiz_id, user_id
  from users
    Where  (quiz_id, id) in
       (
       Select quiz_id, min(id) id
         From users
           Group by quiz_id
       )
Mahdi Sabori
  • 77
  • 3
  • 12