Skip to content Skip to sidebar Skip to footer

Select N Rows With Mixed Values

I have a table with columns like insertTimeStamp, port, data 1 , 20 , 'aaa' 2 , 20 , 'aba' 3 , 20 , '3aa' 4 , 20 , 'aab' 2

Solution 1:

SQL Fiddle Demo

As you can see I create a group_id so group_id = 1 will be the smaller TimeStamp for each port

The second field is time_id so in the ORDER BY after I select all the 1 bring all the 2,3,4 for any port.

SELECT*FROM (
         SELECT*, 
            row_number() over (partitionby "port" orderby "insertTimeStamp") group_id,
            row_number() over (orderby "insertTimeStamp") time_id
         FROM Table1 T
   ) as T
   ORDERBYCASEWHEN group_id =1THEN group_id
               ELSE time_id
            END
   LIMIT 4

OUTPUT

| insertTimeStamp | port | data | group_id | time_id |
|-----------------|------|------|----------|---------|
|               1 |   20 |  aaa |        1 |       1 |
|               2 |   21 |  aza |        1 |       3 |
|              15 |   22 |  2aa |        1 |       8 |
|               2 |   20 |  aba |        2 |       2 |

Solution 2:

Use row_number():

select *
from (
    select insertTimeStamp, port, data
    from (
        select *, row_number() over (partition by port orderby insertTimeStamp) rn
        from a_table
        ) aliasorderby rn, insertTimeStamp
    limit 4
    ) aliasorderby1, 2;

 inserttimestamp | port | data 
-----------------+------+------
               1 |   20 | aaa
               2 |   20 | aba
               2 |   21 | aza
              15 |   22 | 2aa
(4 rows)

SqlFiddle

Post a Comment for "Select N Rows With Mixed Values"