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?
You need to use DISTINCT keyword to select distinct dates from datetime column in a table. Now you can insert some records in the table using insert command. Display all records from the table using select statement.
Use the Query Plan To Confirm Order Notice that the query “DISTINCT TOP 10” includes the first 10 rows from the query from the “DISTINCT” query. From this we know a DISTINCT list is first created, and then the TOP 10 items returned.
Either DISTINCT doesn't work (because the added extended sort key column changes its semantics), or ORDER BY doesn't work (because after DISTINCT we can no longer access the extended sort key column).
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
| 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 |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With