Samik Sengupta
Samik Sengupta

Reputation: 1973

Mysql Select distinct records from latest dates only

This is my table structure -

TABLE : COURSE_LOG

-----------------------------------------------------
|   ID   |   USERNAME   |  COURSE_ID   |    LDATE   |
-----------------------------------------------------
|   1    |     user1    |      22      | 2013-06-01 |
-----------------------------------------------------
|   2    |     user1    |      54      | 2013-06-03 |
-----------------------------------------------------
|   3    |     user1    |      22      | 2013-06-03 |
-----------------------------------------------------
|   4    |     user2    |      71      | 2013-06-04 |
-----------------------------------------------------

I want to pick all of user1's COURSE_ID data distinctly (along with it's date). Since date will vary between two same COURSE_ID entries, I want to pick the row with the more recent date. I am hoping to get a result like this -

-----------------------------
|  COURSE_ID   |    LDATE   |
-----------------------------
|      54      | 2013-06-03 |
-----------------------------
|      22      | 2013-06-03 |
-----------------------------
|      71      | 2013-06-04 |
-----------------------------

And I would not want this -

-----------------------------    
|      22      | 2013-06-01 |    // THIS SHOULD BE OMITTED FROM RESULT BECAUSE THERE
-----------------------------    // IS ANOTHER RECENT ENTRY WITH THE SAME COURSE_ID

I'm using this query -

SELECT DISTINCT(COURSE_ID), LDATE FROM COURSE_LOG
WHERE USERNAME = 'user1' 
AND LDATE = (
    SELECT LDATE 
    FROM COURSE_LOG
    WHERE USERNAME = 'user1' 
    ORDER BY LDATE DESC 
    LIMIT 1
)

But it only picks one row. How do I correct this?

Upvotes: 8

Views: 29718

Answers (2)

Meherzad
Meherzad

Reputation: 8553

Try this query

If you want only for user1 then use this query:

select username, course_id, max(ldate) as date
from tbl 
where username='user1'
group by username, course_id

SQL FIDDLE

| USERNAME | COURSE_ID |       DATE |
-------------------------------------
|    user1 |        22 | 2013-06-03 |
|    user1 |        54 | 2013-06-03 |

If you want to find the latest date for all users then use this query

select username, course_id, max(ldate) as date
from tbl 
group by username, course_id

In this query data of user2 will also be included

| USERNAME | COURSE_ID |       DATE |
-------------------------------------
|    user1 |        22 | 2013-06-03 |
|    user1 |        54 | 2013-06-03 |
|    user2 |        71 | 2013-06-04 |

Upvotes: 24

KaeL
KaeL

Reputation: 3659

You can use MAX:

SELECT  COURSE_ID
    , MAX(LDATE) AS LDATE
    FROM COURSE_LOG
    WHERE USERNAME = 'user1'
    GROUP BY COURSE_ID;

Upvotes: 3

Related Questions