Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select latest row for each group from oracle

I have a table with user comments in a guestbook. Columns are: id, user_id, title, comment, timestamp.

I need to select the latest row for each user. I have tried to do this with group by but havent managed it because i cant select anything else in the same query where i group by user_id:

SELECT user_id, MAX(ts) FROM comments GROUP BY user_id

for example in this query i cant add to also select columns id, tilte and comment. How can this be done?

like image 997
user1985273 Avatar asked Nov 03 '16 14:11

user1985273


People also ask

How do I get the first row of a group in SQL?

To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ). You assign the row numbers within each group (i.e., year).

Can we use Rownum with group by in Oracle?

HAVING refers to properties of groups created by GROUP BY , not to individual rows. You can't use ROWNUM in HAVING any more than you can use BYTES , or any other expression that may have different values for rows within a single group.

How do you select the first row of each unique value of a column?

Generally, here is how to select only the first row for each unique value of a column: Navigate to the Data tab and tap on Advanced under Sort & Filter. In the pop-up catalog, include the list range as the first column and check Unique Records Only. Click OK to select the first row with unique values.

What is the query to fetch last record from the table in Oracle?

Records are not returned in order of anything. and rownum = 1; will get the "last" record. It is the ONLY way.


1 Answers

You can use analytic functions

SELECT *
  FROM (SELECT c.*,
               rank() over (partition by user_id order by ts desc) rnk
          FROM comments c)
 WHERE rnk = 1

Depending on how you want to handle ties (if there can be two rows with the same user_id and ts), you may want to use the row_number or dense_rank function rather than rank. rank would allow multiple rows to be first if there was a tie. row_number would arbitrarily return one row if there was a tie. dense_rank would behave like rank for the rows that tied for first but would consider the next row to be second rather than third assuming two rows tie for first.

like image 168
Justin Cave Avatar answered Sep 29 '22 07:09

Justin Cave