Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying results by group and rank using SQL

I have a table with the following structure:

id          timestamp       area
717416915   18:30:53.063    25.691601
717416915   18:31:34.863    31.200506
717416915   18:32:23.665    25.690088
1994018321  18:32:45.467    37.409171
1994018321  18:33:19.612    37.409171
424164505   18:36:16.634    18.22091
424164505   18:36:36.899    18.210754
424164505   18:37:08.614    19.829266
2394018356  18:37:27.231    79.31705

What I want to do is to summarize the values in such a way that I can identify the area per id, ordered by timestamp. For example if I wanted the first area value it would be the following:

id          timestamp       area_1
717416915   18:30:53.063    25.691601
1994018321  18:32:45.467    37.409171
424164505   18:36:16.634    18.22091
2394018356  18:37:27.231    79.31705

And if I wanted to get the second area value per id it would be the following:

id          timestamp       area_2
717416915   18:31:34.863    31.200506
1994018321  18:33:19.612    37.409171
424164505   18:36:36.899    18.210754

I understand that I need to sort by time, and then identify the first value per id. I don't quite understand how to do this. What I have tried doing is the following (which is not running, as I am still a little unclear on how to use the OVER function).

WITH T AS (
    SELECT * OVER(PARTITION BY a.id ORDER BY a.timestamp) AS rnk
    FROM mytable AS a
) 
SELECT area as area_1
FROM T
WHERE rnk = 1
GROUP BY a.id
ORDER BY a.timestamp;

I was planning to use rnk=2 etc, to get subsequent area values per id.

like image 415
djq Avatar asked May 05 '12 23:05

djq


People also ask

Can we use rank and group by together?

we can use rank function and group by in the same query set but all the columns should be contained in either aggregate function or the Group by clause.

What does rank () do in SQL?

Returns the rank of each row within the partition of a result set. The rank of a row is one plus the number of ranks that come before the row in question. ROW_NUMBER and RANK are similar. ROW_NUMBER numbers all rows sequentially (for example 1, 2, 3, 4, 5).

How do I write a ranked query in SQL?

We use ROW_Number() SQL RANK function to get a unique sequential number for each row in the specified data. It gives the rank one for the first row and then increments the value by one for each row. We get different ranks for the row having similar values as well.


1 Answers

The syntax should be as follows:

SELECT RANK() OVER(PARTITION BY a.id ORDER BY a.timestamp) AS rnk
like image 151
McGarnagle Avatar answered Nov 08 '22 23:11

McGarnagle