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 > Selecting Grouped Row

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 07-18-09, 08:35
cpriest cpriest is offline
Registered User
 
Join Date: Jul 2009
Posts: 1
Question Selecting Grouped Row

I'm trying to figure out how to choose the row that a grouped rows value will represent.

Input Rows:
Code:
Table1
| ID | JoinID | SourceID | Timestamp             |
--------------------------------------------------
| 1  | 1      | 1        | '2009-07-16 11:48:32' |
| 2  | 1      | 7        | '2009-07-17 14:32:11' |
| 3  | 1      | 3        | '2009-07-18 07:14:47' |
| 4  | 2      | 6        | '2009-07-14 16:12:23' |
| 5  | 2      | 4        | '2009-07-18 10:32:07' |
Result Rows Desired:
Code:
Table1
| ID | JoinID | SourceID | Timestamp             |
--------------------------------------------------
| 3  | 1      | 3        | '2009-07-18 07:14:47' |
| 5  | 2      | 4        | '2009-07-18 10:32:07' |
You see I want to do something like this:
Code:
SELECT *
FROM Table1
GROUP BY JoinID
But specifically I want the 'rolled up' row to be represented by the row with the highest timestamp. So effectively the JoinID, SourceID and ID are all the values in the row with the highest Timestamp value.

Any ideas on the proper way to do this?
Reply With Quote
  #2 (permalink)  
Old 07-18-09, 08:59
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,534
Quote:
Originally Posted by cpriest
But specifically I want the 'rolled up' row to be represented by the row with the highest timestamp.
there are many ways to do it

here are eleven ways: ~jk groupwise max

and here are five more (written for SQL Server, including analytical/windowing solutions which don't apply to mysql): Less Than Dot - Blog - Including an Aggregated Column's Related Values

__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
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