Question

Here is my data:

client_addr |  start  
------------+-----------
 1.2.3.4    |   12:54:06
 1.2.3.4    |   12:55:00
 5.6.7.8    |   12:54:06
 5.6.7.8    |   13:00:00
 5.6.7.8    |   11:00:00
 9.9.9.9    |   14:00:00

I want to sort it and rank it like this:

  RK | client_addr |    start  
-----+-------------+-----------
  1  |  1.2.3.4    |  12:54:06
  1  |  5.6.7.8    |  11:00:00
  1  |  9.9.9.9    |  14:00:00
  2  |  1.2.3.4    |  12:55:00
  2  |  5.6.7.8    |  12:54:06
  3  |  5.6.7.8    |  13:00:00

I have tried this

SELECT 
    rank() over (order by start ASC) as RK,
    client_addr,
    start
FROM
    my_table

but it doesn't work.

Was it helpful?

Solution

It seems this is what you're looking for:

SELECT
  rank() OVER (PARTITION BY client_addr ORDER BY start) AS RK,
  client_addr,
  start
FROM my_table
ORDER BY RK, inet(client_addr)

Output:

| RK | CLIENT_ADDR |                     START |
|----|-------------|---------------------------|
|  1 |     1.2.3.4 | January, 01 1970 12:54:06 |
|  1 |     5.6.7.8 | January, 01 1970 11:00:00 |
|  1 |     9.9.9.9 | January, 01 1970 14:00:00 |
|  2 |     1.2.3.4 | January, 01 1970 12:55:00 |
|  2 |     5.6.7.8 | January, 01 1970 12:54:06 |
|  3 |     5.6.7.8 | January, 01 1970 13:00:00 |

Note you'll have to user the inet function if you want the IP address 10.12.13.14 to be sorted after the 9.9.9.9 instead of after 1.2.3.4 (see the fiddle below).

Fiddle here.

OTHER TIPS

AFAIK, is not possible to be done in one single query, but it is easy to do with window function and cte. Maybe an easiest query can be created, but this one works.

create table my_table (client_addr varchar, start time);
insert into my_table values ('1.2.3.4', '12:54:06'), ('1.2.3.4','12:55:00'), ('5.6.7.8', '12:54:06'), ('5.6.7.8', '13:00:00'), ('5.6.7.8', '11:00:00'), ('9.9.9.9', '14:00:00');

with t as (select rank() over (partition by client_addr order by start) as RK, client_addr, start from my_table)
select RK, client_addr, start from t order by RK;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top