Sql 获取表中每个值具有最小时间间隔的行

Sql 获取表中每个值具有最小时间间隔的行,sql,postgresql,aggregate-functions,greatest-n-per-group,Sql,Postgresql,Aggregate Functions,Greatest N Per Group,这是我的桌子: Start Time Stop time extension ---------------------------------------------------------- 2014-03-03 10:00:00 2014-03-03 11:00:00 100 2014-03-03 10:00:00 2014-03-03 12:00:00 100 2014-03-05 10:00:

这是我的桌子:

Start Time Stop time extension ---------------------------------------------------------- 2014-03-03 10:00:00 2014-03-03 11:00:00 100 2014-03-03 10:00:00 2014-03-03 12:00:00 100 2014-03-05 10:00:00 2014-03-05 11:00:00 200 2014-03-03 10:00:00 2014-03-03 13:00:00 100 2014-03-05 10:00:00 2014-03-05 12:00:00 200 2014-03-05 10:00:00 2014-03-05 13:00:00 200 我希望获得每个扩展的最小时间间隔:

Start Time Stop time Extension ------------------------------------------------------------- 2014-03-03 10:00:00 2014-03-03 11:00:00 100 2014-03-05 10:00:00 2014-03-05 11:00:00 200
如何编写sql?

不确定您到底想要什么,但最小的间隔是

select min(stop_time - start_time) 
from the_table
如果您还需要这两列:

select start_time, stop_time, duration
from (
   select start_time, 
          stop_time,
          stop_time - start_time as duration,
          min(stop_time - start_time) as min_duration
   from the_table
) t
where duration = min_duration;
如果多行具有相同的持续时间,则上述操作将产生多行。如果您不想这样做,您可以使用:

select start_time, stop_time, duration
from (
   select start_time, 
          stop_time,
          stop_time - start_time as duration,
          row_numer() over (order by stop_time - start_time) as rn
   from the_table
) t
where rn = 1;
好的,更新之后:

CREATE TABLE fluff2
        ( id SERIAL NOT NULL PRIMARY KEY
        , starttime TIMESTAMP NOT NULL
        , stoptime TIMESTAMP NOT NULL
        , bagger INTEGER NOT NULL
        );
;

INSERT INTO fluff2(starttime,stoptime, bagger) VALUES
  ( '2014-03-03 10:00:00', '2014-03-03 11:00:00',100)
, ( '2014-03-03 10:00:00', '2014-03-03 12:00:00',100)
, ( '2014-03-05 10:00:00', '2014-03-05 11:00:00',200)
, ( '2014-03-03 10:00:00', '2014-03-03 13:00:00',100)
, ( '2014-03-05 10:00:00', '2014-03-05 12:00:00',200)
, ( '2014-03-05 10:00:00', '2014-03-05 13:00:00',200)
        ;

SELECT * FROM fluff2 fl
WHERE NOT EXISTS (
        SELECT *
        FROM fluff2 nx
        WHERE nx.bagger = fl.bagger
        AND AGE(nx.stoptime,nx.starttime) < AGE(fl.stoptime,fl.starttime)
        );
我会使用order by和limit:


这将为您提供表中所有列的最短持续时间。

根据您更新的问题,要获取包含所有原始列且每个扩展的时间间隔最短的行,Postgres特定的DISTINCT ON应该最方便:

SELECT DISTINCT ON (extension)
       start_time, stop_time, extension
FROM   tbl
ORDER  BY extension, (stop_time - start_time);
有关答案的详情如下:

获得表中的最小时间间隔或每次首发的最小时间间隔?现在我们只需要Craig Ringer投入,@gameip将所有PostgreSQL高命中率玩家集合在一个帖子中,甚至在命中10次代表之前。肯定会有一个金徽章吗-[;-d问题不清楚:您需要最小间隔,或者需要具有最小间隔的行?或者其他什么?我已经添加了有关问题的更多详细信息。事实上,这不仅仅是获得一条记录。我希望根据扩展名获得结果。谢谢!
select t.*
from table t
order by stop_time - start_time asc
limit 1;
SELECT DISTINCT ON (extension)
       start_time, stop_time, extension
FROM   tbl
ORDER  BY extension, (stop_time - start_time);