如何使用包含它的'status'='start'来获取以获得结尾的id开头的一组kol_name。 这意味着,我从外部得到'id'并希望从'start'包含一组列到没有他的下一个'start',或者最后'add',结果用于动态SQL
id kol_name status
------------------------------
44 kol_name_1 add
43 kol_name_2 add
42 kol_name_3 add
41 kol_name_4 start
40 kol_name_5 add
39 kol_name_6 start
37 kol_name_7 start
我的预期输出是当我得到id 44
kol_name
--------------------
kol_name_1
kol_name_2
kol_name_3
kol_name_4
我的预期输出是当我得到你的身份37
kol_name
--------------------
kol_name_7
我的预期输出是当我得到id 39
kol_name
--------------------
kol_name_5
kol_name_6
我该怎么做?
答案 0 :(得分:1)
嗯。一种方法是计算第一个开始“在”给定的id之后(“之后”似乎是一个较小的id,这就是为什么我把它放在引号中)。然后,您可以使用简单的逻辑:
select t.*
from t cross join
(select max(id) as startid
from t
where id <= 44 and status = 'start'
) tt
where t.id <= 44 and t.id >= tt.startid;
如果您只想在查询中提及“44”:
select t.*
from t cross join
(select theid, max(id) as startid
from t cross join (select 44 as theid from dual)
where id <= theid and status = 'start'
) tt
where t.id <= tt.theid and t.id >= tt.startid;
编辑:
此代码仅返回一行:
with t as (
select 44 as id, 'kol_name_1' as kol_name, 'add' as status from dual union all
select 43, 'kol_name_2', 'add' from dual union all
select 42, 'kol_name_3', 'add' from dual union all
select 41, 'kol_name_4', 'start' from dual union all
select 40, 'kol_name_5', 'add' from dual union all
select 39, 'kol_name_6', 'start' from dual union all
select 37, 'kol_name_7', 'start' from dual
)
select t.*
from t cross join
(select max(id) as startid
from t
where id <= 39 and status = 'start'
) tt
where t.id <= 39 and t.id >= tt.startid;
Here是一个SQL小提琴
编辑II;
哦,你想要带有39的两个行。如果是这种情况,请使用no equality更改startid
的定义:
select t.*
from t cross join
(select max(id) as startid
from t
where id < 44 and status = 'start'
) tt
where t.id <= 44 and t.id >= tt.startid;