Select SQL 中的一行 table 仅当值在 table 的下几行中时?
Select a row in a SQL table only if a value is in the next few rows of the table?
如何从 SQL table 中 select 具有特定列值的行,但前提是两个特定列值之一在接下来的五行中?
例如,我有一个 table,如下所示:
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
我想要 select 行 where action=1,当且仅当在 table where action = 4 或 action = 6 的下五行中有一行。在上面 table 这将 return 第一行(id=1,纽约),只是因为行 id=4(波士顿,action=4)而不是因为行 id=7(达拉斯,行动=6)
使用的一种方法window 功能:
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
使用window函数:
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
如何从 SQL table 中 select 具有特定列值的行,但前提是两个特定列值之一在接下来的五行中?
例如,我有一个 table,如下所示:
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
我想要 select 行 where action=1,当且仅当在 table where action = 4 或 action = 6 的下五行中有一行。在上面 table 这将 return 第一行(id=1,纽约),只是因为行 id=4(波士顿,action=4)而不是因为行 id=7(达拉斯,行动=6)
使用的一种方法window 功能:
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
使用window函数:
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