gpt4 book ai didi

sql - 选择时间范围外的不同行

转载 作者:行者123 更新时间:2023-12-04 22:15:50 24 4
gpt4 key购买 nike

我正在尝试使用 SQL 根据一个条目与下一个条目之间的时间差来选择不同的数据条目。用一个例子更容易解释:

我的数据表有

Part    DateTime   
123 12:00:00
123 12:00:05
123 12:00:06
456 12:10:23
789 12:12:13
123 12:14:32

我想返回所有行,只要有一个限制,即如果有多个条目具有相同的“零件”编号,我只想检索相差至少 5 分钟的条目。

查询应该返回:

Part    DateTime   
123 12:00:00
456 12:10:23
789 12:12:13
123 12:14:32

我使用的代码如下:

SELECT data1.*, to_char(data1.scan_time, 'yyyymmdd hh24:mi:ss') 

FROM data data1

where exists
(
select *

from data data2

where data1.part_serial_number = data2.part_serial_number AND
data2.scan_time + 5/1440 >= data1.scan_time
and data2.info is null
)

order by to_char(data1.scan_time, 'yyyymmdd hh24:mi:ss'), data1.part_serial_number

不幸的是,这不起作用。有谁知道我做错了什么或可以建议替代方法??

谢谢

最佳答案

救援分析函数。

您可以使用分析函数 LEAD 获取零件下一行的数据。

SQL> ed
Wrote file afiedt.buf

1 with x as (
2 select 123 part, timestamp '2011-12-08 00:00:00' ts
3 from dual
4 union all
5 select 123, timestamp '2011-12-08 00:00:05'
6 from dual
7 union all
8 select 123, timestamp '2011-12-08 00:00:06'
9 from dual
10 union all
11 select 456, timestamp '2011-12-08 00:10:23'
12 from dual
13 union all
14 select 789, timestamp '2011-12-08 00:12:13'
15 from dual
16 union all
17 select 123, timestamp '2011-12-08 00:14:32'
18 from dual
19 )
20 select part,
21 ts,
22 lead(ts) over (partition by part order by ts) next_ts
23* from x
SQL> /

PART TS NEXT_TS
---------- ------------------------------- -------------------------------
123 08-DEC-11 12.00.00.000000000 AM 08-DEC-11 12.00.05.000000000 AM
123 08-DEC-11 12.00.05.000000000 AM 08-DEC-11 12.00.06.000000000 AM
123 08-DEC-11 12.00.06.000000000 AM 08-DEC-11 12.14.32.000000000 AM
123 08-DEC-11 12.14.32.000000000 AM
456 08-DEC-11 12.10.23.000000000 AM
789 08-DEC-11 12.12.13.000000000 AM

6 rows selected.

完成后,您就可以创建一个内联 View ,并只需选择下一个日期比当前日期晚 5 分钟以上的那些行。

SQL> ed
Wrote file afiedt.buf

1 with x as (
2 select 123 part, timestamp '2011-12-08 00:00:00' ts
3 from dual
4 union all
5 select 123, timestamp '2011-12-08 00:00:05'
6 from dual
7 union all
8 select 123, timestamp '2011-12-08 00:00:06'
9 from dual
10 union all
11 select 456, timestamp '2011-12-08 00:10:23'
12 from dual
13 union all
14 select 789, timestamp '2011-12-08 00:12:13'
15 from dual
16 union all
17 select 123, timestamp '2011-12-08 00:14:32'
18 from dual
19 )
20 select part,
21 ts
22 from (
23 select part,
24 ts,
25 lead(ts) over (partition by part order by ts) next_ts
26 from x )
27 where next_ts is null
28* or next_ts > ts + interval '5' minute
SQL> /

PART TS
---------- -------------------------------
123 08-DEC-11 12.00.06.000000000 AM
123 08-DEC-11 12.14.32.000000000 AM
456 08-DEC-11 12.10.23.000000000 AM
789 08-DEC-11 12.12.13.000000000 AM

关于sql - 选择时间范围外的不同行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8436678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com