If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > SELECT one from each?

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 10-07-03, 09:11
jackfp jackfp is offline
Registered User
 
Join Date: Oct 2003
Posts: 1
SELECT one from each?

Table like this:
date | id | value
2003-10-01 | A | 100
2003-10-02 | A | 300
2003-10-03 | A | 200
2003-10-01 | B | 300
2003-10-02 | B | 100
2003-10-02 | C | 200

Should return result like this:
date | id | value
2003-10-03 | A | 200
2003-10-02 | B | 100
2003-10-02 | C | 200

Point is to select the newest record (by date) for each of the id (only one for each id)

SELECT DISTINCT... will return all records.

SELECT ... ORDER BY date DESC LIMIT 1 will return just 1 record.

SELECT MAX(date), id, value FROM table GROUP BY id
will return unpredictable (some times correct) result.

Any Solutions?

Thanks
Reply With Quote
  #2 (permalink)  
Old 10-07-03, 10:23
cvandemaele cvandemaele is offline
Registered User
 
Join Date: Oct 2003
Location: Switzerland
Posts: 140
Don't know much about MySQL, but your syntax

SELECT MAX(date), id, value FROM table GROUP BY id

would be invalid in MSSQL and Oracle. The column "value" should be included in the GROUP BY expression, or removed from the select list.

Regards.

CVM.
Reply With Quote
  #3 (permalink)  
Old 10-07-03, 11:29
gnet gnet is offline
Registered User
 
Join Date: Jul 2003
Posts: 30
Re: SELECT one from each?

The below should work so long as the value is always three in length, or you could rewrite this otherwise.

select id,
max(date) as date,
right( max( concat(date, value)) ,3) as value
from test
group by id;


http://www.mysql.com/doc/en/example-...group-row.html
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On