Re: SQL query problem of a Quiz program

From: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
To: Arup Rakshit <aruprakshit1987(at)outlook(dot)com>, "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: SQL query problem of a Quiz program
Date: 2016-12-17 17:49:17
Message-ID: c2ead5b4-0d7f-98e9-c1cb-1add4687b8ba@aklaver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 12/17/2016 07:25 AM, Arup Rakshit wrote:
> Hi,
>
> Here is a sample data from table "quiz_results":
>
> id | question_id | user_id
> ----+-------------+------------
> 2 | 25 | 5142670086
> 3 | 26 |
> 4 | 26 |
> 5 | 27 |
> 6 | 25 | 5142670086
> 7 | 25 | 5142670086
> 8 | 25 | 5142670086
> 9 | 26 |
> 10 | 40 | 5142670086
> 11 | 29 | 5142670086
>
>
> As you see above question id 25 appeared more than once. This is basically a quiz result table where for users as they answered. question_id 25 always the first questions. Any user can go though the quiz N number of time. So, I want to find the last occurrence of the question_id 25 for any specific user in the table, and select that and all answers the users gave after this till the end of the quiz. Any idea how to solve it in a single efficient query. My all try didn't work out.

test=# create table quiz(id int, question_id int, user_id bigint);
CREATE TABLE

est=# select * from quiz order by id, question_id;

id | question_id | user_id
----+-------------+------------
2 | 25 | 5142670086
3 | 26 | NULL
4 | 26 | NULL
4 | 26 | NULL
5 | 27 | NULL
6 | 25 | 5142670086
7 | 25 | 5142670086
8 | 25 | 5142670086
10 | 40 | 5142670086
11 | 29 | 5142670086
(10 rows)

test=# select
*
from
quiz
where
user_id = 5142670086
and
id >=
(select
max(id)
from
quiz
where
user_id = 5142670086
and
question_id = 25)
order by
question_id;

id | question_id | user_id
----+-------------+------------
8 | 25 | 5142670086
11 | 29 | 5142670086
10 | 40 | 5142670086
(3 rows)

>
>
>
> --------------------
> Regards,
> Arup Rakshit
>

--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Simon Charette 2016-12-17 18:01:40 Re: Recursive row level security policy
Previous Message Melvin Davidson 2016-12-17 16:02:40 Re: SQL query problem of a Quiz program