繁体   English   中英

仅当值在表的下几行中时才选择 SQL 表中的一行?

[英]Select a row in a SQL table only if a value is in the next few rows of the table?

如何从具有特定列值的 SQL 表中选择行,但前提是两个特定列值之一在接下来的五行中?

例如,我有一个如下所示的表:

id | name     | action 
-----------------------
 1 | New York |  1 
 2 | Boston   |  3
 3 | Dallas   |  2
 4 | Boston   |  4
 5 | New York |  2
 6 | Chicago  |  5
 7 | Dallas   |  6

我想选择 action=1 的行,当且仅当表的下五行中有一行,其中 action = 4 或 action = 6。在上表中,这将返回第一行(id= 1,纽约),仅因为行 id=4(波士顿,动作=4)而不是因为行 id=7(达拉斯,动作=6)

一种方法使用窗口函数:

select t.*
from (select t.*,
             count(*) filter (where action in (4, 6)) over (order by id rows between current row and 5 following) as cnt_action_4_6
      from t
     ) t
where action = 1 and cnt_action_4_6 > 0

使用窗口函数:

select *
from (
    select t.*,
        count(*) filter(where action in (4, 6)) over(order by id rows between 1 following and 5 following) cnt
    from mytable t
) t
where action = 1 and cnt > 0

暂无
暂无

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

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