0

How do I ensure, when I GROUP BY QID, that only the most recent row is returned?

ID, QID, VALUE, TIMESTAMP
45,1,Male,1362044759
58,1,Female,1362045122
59,1,Male,1362045149
60,1,Female,1362045153
82,1,Female,1362045863
83,1,Female,1362045887
92,1,Male,1362046012
101,1,Female, 1362046401

SELECT ID, QID, VALUE, TIMESTAMP FROM table GROUP BY ID

...returns the first row. I can't simply do a LIMIT 1, as this is just an example, there are lots of QIDs in the table, which are all grouped.

Thanks.

ojsglobal
  • 525
  • 1
  • 6
  • 31

3 Answers3

1

I'm assuming here you want the "latest" row for each QID. You would normally use a derived-table subquery to get each QID's latest TIMESTAMP value and then join on that:

SELECT ...
FROM myTable AS t
INNER JOIN (SELECT QID, MAX(`TIMESTAMP`) AS MaxT FROM myTable GROUP BY QID) l
    ON t.QID = l.QID AND l.maxT = t.`TIMESTAMP`

This is also assuming your TIMESTAMP column increases as time goes on.

lc.
  • 113,939
  • 20
  • 158
  • 187
0

You could use 'GROUP_CONCAT' in order to extract grouped data.

SELECT GROUP_CONCAT(ID ORDER BY TIMESTAMP DESC) AS latest_id
kaspernj
  • 1,243
  • 11
  • 16
0

If you want the most recent record returned:

SELECT *
FROM TBL
ORDER BY `TIMESTAMP` DESC
LIMIT 1;

Otherwise, if you want to get the most recent record for each group of QID check this Stack Overflow Post that treat your same problem with optimal solutions.

Community
  • 1
  • 1
araknoid
  • 3,065
  • 5
  • 33
  • 35