user1537779
user1537779

Reputation: 2331

Select a row with least value of a column using where and group by

Sample table:

id------user_id------grade_id------time_stamp

1---------100----------1001---------2013-08-29 15:07:38

2---------101----------1002---------2013-08-29 16:07:38

3---------100----------1001---------2013-08-29 17:07:38

4---------102----------1003---------2013-08-29 18:07:38

5---------103----------1004---------2013-08-29 19:07:38

6---------105----------1002---------2013-08-29 20:07:38

6---------100----------1002---------2013-08-29 21:07:38

I want to select rows whose user_id = 100 group by grade_id only if its time_stamp is least for that particular grade_id.

so, from the above table, it should be:

row 1 because its time_stamp is least for that value of grade_id(1001)

but not row 2 because I only want 1 row for a particular grade_id

also not row 6 because that particular grade_id has least value for user_id 105.

I tried few things, which are too basic and obviously not worth posting.

Thank You

Upvotes: 1

Views: 975

Answers (2)

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115520

SELECT t.*
FROM tableX AS t
  JOIN
    ( SELECT grade_id, MIN(time_stamp) AS time_stamp
      FROM tableX
      GROUP BY grade_id
    ) AS g
      ON  g.grade_id = t.grade_id
      AND g.time_stamp = t.time_stamp
WHERE t.user_id = 100 ;

Upvotes: 1

You could try nested queries:

SELECT grade_id, COUNT(grade_id) FROM SAMPLE_TABLE ST WHERE time_stamp = (SELECT MIN(time_stamp) FROM SAMPLE_TABLE STT WHERE STT.grade_id = ST.grade_id) AND user_id = 100 GROUP BY grade_id;  

In this case, the nested query will give you the minimun timestamp for each specific 'grade_id' and you can use it in your WHERE filter.

Upvotes: 1

Related Questions