简体   繁体   English

SQL 比较同一张表多行记录

[英]SQL compare records in multiple rows in same table

I have table with: Port_nbr, Pair, length, add_date.我有一张桌子:Port_nbr、Pair、length、add_date。 example:例子:

port_nbr        | 4
pair            | pairC
length          | 33.12
add_date        | 2020-06-16 00:01:13.237164

There is 4 pairs intotal ( A,B,C,D) and each port_nbr has a pair(AD) atleast once.总共有 4 对 (A,B,C,D),每个 port_nbr 至少有一对 (AD)。 It means, each port_nbr can be multiple times.这意味着,每个 port_nbr 可以是多次。 I need to find out if that port any pair length is increased by 30m.我需要确定该端口的任何对长度是否增加了 30m。 To do it, i must order each port_nbr by date, because i need to compare 1 record with next record and find out when it increased by 30m为此,我必须按日期对每个 port_nbr 进行排序,因为我需要将 1 条记录与下一条记录进行比较,并找出它何时增加了 30m

example: RECORD 1示例:记录 1

port_nbr | 1                          
pair     | pairA
length   | 30.00
add_date | 2020-06-16 00:01:13.237164

RECRORD 2记录 2

port_nbr | 1                              
pair     | pairA
length   | 65.00
add_date | 2020-06-16 00:02:13.237164

expected output- Length increased on: port 1, pairA, 2020-06-16 00:02:13.237164 by 35m预期输出 - 长度增加:端口 1,pairA,2020-06-16 00:02:13.237164 by 35m

There is hundreds of records and i have to compare one to another record, but it has to be same port and pair.有数百条记录,我必须将一条记录与另一条记录进行比较,但它必须是相同的端口和配对。

Everything i have right now is:我现在拥有的一切是:

Select *
from diags a join
     (SELECT port_nbr, count(*) from diags group by port_nbr having count(*) > 1 ) b
     on a.port_nbr = b.port_nbr
order by a.port_nbr

It would help a lot if someone could explain what i should to try add to get expected result.如果有人可以解释我应该尝试添加什么以获得预期的结果,那将有很大帮助。

I think you just want lead() :我想你只想要lead()

select d.*
from (select d.*,
             lead(length) over (partition by port_nbr, pair order by add_date) as next_length
      from diags d
     ) d
where next_length > length + 30;

This gets the next length for the same part/pair combo and returns rows where the next value exceeds your threshold.这将获取相同部分/对组合的下一个长度,并返回下一个值超过阈值的行。

With LAG() window function:使用LAG() window function:

select port_nbr, pair, length, add_date, diff
from (
  select *, length - lag(length) over (partition by port_nbr, pair order by add_date) diff
 from tablename
) t
where diff > 30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM