选择具有混合值的N行

时间:2015-10-01 16:08:09

标签: sql postgresql select

我有一个包含

列的表格
insertTimeStamp, port, data
1              , 20  , 'aaa'
2              , 20  , 'aba'
3              , 20  , '3aa'
4              , 20  , 'aab'
2              , 21  , 'aza'
5              , 21  , 'aha'
8              , 21  , 'aaa'
15             , 22  , '2aa'

现在我需要来自该表的 N 行(Say 4),由insertTimeStamp命令asc。 但是如果可能的话,我想从不同的port获得它们。

所以结果应该是:

1              , 20  , 'aaa'
2              , 20  , 'aba'
2              , 21  , 'aza'
15             , 22  , '2aa'

如果port中的值不够,我希望选择余下insertTimeStamp的值。

2 个答案:

答案 0 :(得分:2)

<强> SQL Fiddle Demo

如您所见,我创建了group_id,因此group_id = 1将是每个端口的较小TimeStamp

第二个字段为time_id,因此在我选择所有ORDER BY之后1为所有端口带来2,3,4

   SELECT *
   FROM (
         SELECT *, 
            row_number() over (partition by "port" order by "insertTimeStamp") group_id,
            row_number() over (order by "insertTimeStamp") time_id
         FROM Table1 T
   ) as T
   ORDER BY CASE 
               WHEN group_id = 1 THEN group_id
               ELSE time_id
            END
   LIMIT 4

<强>输出

| 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 |

答案 1 :(得分:1)

使用row_number():

select *
from (
    select insertTimeStamp, port, data
    from (
        select *, row_number() over (partition by port order by insertTimeStamp) rn
        from a_table
        ) alias
    order by rn, insertTimeStamp
    limit 4
    ) alias
order by 1, 2;

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

SqlFiddle