|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
I have this simple table:
ID------DATE-------GRP 1----2004-08-02----1 2----2004-08-03----1 3----2004-10-17----3 4----2004-08-02----2 5----2003-02-12----2 6----2004-02-03----2 7----2004-01-20----1 8----2004-07-04----3 I want select last DATE in each GRP When I execute this SQL query: SELECT *,max(DATE) as max_date FROM table group by GRP order by max_date desc; I'll receive result: id, date, grp 8,2004-10-17,3 7,2004-08-03,1 5,2004-08-02,2 DATE and GRP are right but ID isn't correct. What's wrong??? I have no idea ![]() |
|
#2
|
|||
|
|||
|
You can't group by GRP and also select ID. This doesn't make sense, because (to the DB) you might have two IDs with the same maximum DATE and GRP.
First, you may want to SELECT the maximum DATE per GRP. Code:
SELECT grp, max(date) as max_date FROM table GROUP BY grp Now you may use this query to join it with another query containing the IDs: Code:
SELECT a.id, a.grp, a.date
FROM table a, (SELECT grp, max(date) AS max_date FROM table GROUP BY grp) b
WHERE a.grp = b.grp AND a.date = b.max_date
|
![]() |
| Viewing: Dev Articles Community Forums > Databases > General SQL Development > select MAX(DATETIME) problem |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|