mysql 根据SQL中的结果查找下一行和上一行

vhmi4jdf  于 2023-04-05  发布在  Mysql
关注(0)|答案(2)|浏览(385)

在这个示例表fruits中,我想获取high_low_adjstmnt〈0的前一行、当前行和下一行。

Table

id  name    low high    high_low_adjstmnt      volume
1   Apple   5   3         -2                   1000
2   Orange  6   9          3                   2000
3   Banana  13  17         4                   3000
4   Avocado 11  19         8                   4000
5   Berry   21  17        -4                   5000
6   Peach   7   9          2                   6000
7   Mango   9   14         5                   7000
8   Grape   18  11         7                   8000
9   Kiwi    14  13        -1                   9000

所需输出结果

id  name    low high    high_low_adjstmnt      volume
1   Apple   5   3         -2                   1000
2   Orange  6   9          3                   2000
4   Avocado 11  19         8                   4000
5   Berry   21  17        -4                   5000
6   Peach   7   9          2                   6000
8   Grape   18  11         7                   8000
9   Kiwi    14  13        -1                   9000

我如何在查询中得到这个结果?

ovfsdjhp

ovfsdjhp1#

我认为有几种方法可以实现这一点。也许,你可以使用LAG()LEAD()函数来获取上一行和下一行的值,然后使用cte(或派生表)来过滤它们,如下所示:

WITH cte AS (
SELECT *,
       LAG(high_low_adjstmnt) OVER (ORDER BY id) PreviousRow,
       LEAD(high_low_adjstmnt) OVER (ORDER BY id) NextRow
   FROM Table1)

SELECT * 
  FROM cte
WHERE (high_low_adjstmnt < 0 
         OR PreviousRow < 0
         OR NextRow < 0);

Demo fiddle

r3i60tvu

r3i60tvu2#

您可以使用条件t.id = t2.id - 1 or t.id = t2.id or t.id = t2.id + 1执行self-join以获取上一行、当前行和下一行。

select t2.*
from mytable t
inner join mytable t2 on t.id = t2.id - 1 or t.id = t2.id or t.id = t2.id + 1
where t.high_low_adjstmnt < 0

结果:

id  name    low high    high_low_adjstmnt   volume
1   Apple   5   3   -2  1000
2   Orange  6   9   3   2000
4   Avocado 11  19  8   4000
5   Berry   21  17  -4  5000
6   Peach   7   9   2   6000
8   Grape   18  11  7   8000
9   Kiwi    14  13  -1  9000

Demo here

相关问题