Postgres Sql在30分钟左右的时间戳内查询没有记录

时间:2017-07-12 19:44:06

标签: sql postgresql

我正在尝试编写一个Postgres sql,它将在特定时间戳的30分钟内为我提供航班。

我的SQL看起来像:

"从lk_merged a中选择计数(distinct(gufi))为No_of_airplanes where(a.on_actual介于(a.on_actual - (20 * interval' 1分钟')之间)和(a.on_actual +(40 * interval' 1分钟'))) 由a.on_actual"

组成

请建议如何让这些没有飞机。

我的桌子上有gufi作为飞机id,on_actual_timelanding。

我有什么: gufi(plane_id),时间
3432343,12:33:89
2565656,12:44:45
3242234,1:05:23

输出应该是这样的,在时间戳之前和之后的20分钟内有一个新列建议no_of_planes_around

Gufi(plane_id),时间戳,No_of飞机周围 3432343,12:33:89,1 2565656,12:44:45,2 3242234,1:05:23,1

如果没有自我加入,请提出建议。

由于 爱Tyagi

1 个答案:

答案 0 :(得分:0)

如果使用COUNT()作为窗口函数,则不能使用COUNT(DISTINCT ...),如果你试图得到错误" 0A000:DISTINCT没有实现窗口函数& #34 ;.因此,为了计算这个计数的不同,并在每行输出上输出,我建议使用CROSS JOIN LATERAL。

注意我在您的小数据示例中不确定1:05:23 = 01:05:23或13:05:23所以我包括了两者。

CREATE TABLE mytable(
   plane_id   INTEGER  NOT NULL 
  ,plane_time TIME NOT NULL
)
\\
INSERT INTO mytable(plane_id,plane_time) VALUES (3432343,TO_TIMESTAMP('12:33:89', 'HH24:MI:SS')::TIME)\\
INSERT INTO mytable(plane_id,plane_time) VALUES (2565656,TO_TIMESTAMP('12:44:45', 'HH24:MI:SS')::TIME)\\
INSERT INTO mytable(plane_id,plane_time) VALUES (3242234,TO_TIMESTAMP('01:05:23', 'HH24:MI:SS')::TIME)\\
INSERT INTO mytable(plane_id,plane_time) VALUES (3242234,TO_TIMESTAMP('13:05:23', 'HH24:MI:SS')::TIME)\\

select * 
from mytable t1
cross join lateral (
    select count(distinct plane_id) No_of_planes_around
    from mytable t2 
    where t2.plane_time between t1.plane_time - interval '20 minutes' and t1.plane_time + interval '40 minutes'
    --and t1.plane_id <> t2.plane_id
    ) cjl
\\

此外,我还不确定计数是否应包含当前行的平面,因此我将其包括在内,但您可以通过制作行&#34;和t1.plane_id&lt;&gt;来排除它。 t2.plane_id&#34;在查询中处于活动状态。

相关问题