我的表request_step包含下面的虚拟信息
id,request_id,state,name,step_number
*2,1,pending,step a,1
1,1,pending,step b,2
3,1,pending,step c,3
4,1,pending,step d,4
5,2,accepted,step a,1
6,2,accepted,step b,2
*7,2,pending,step c,3
8,2,pending,step d,4
9,7,accepted,step a,1
10,7,accepted,step b,2
11,7,accepted,step c,3
14,7,accepted,step d,4
*13,7,pending,step e,5
12,7,pending,step f,6
15,8,accepted,step a,1
17,8,rejected,step b,2
16,8,pending,step c,3 --> not this one because the previous step is rejected
18,9,accepted,step a,1
19,9,accepted,step b,2
我想对每个request_id进行下一步(待处理状态),并且前面的步骤不得具有任何拒绝状态。我在行前标记了一个星号,以显示要查询的那个
我已经有一个sql脚本可以将所有后续步骤都返回给我,但是我找不到解决方案来检查先前的步骤是否被拒绝
select rs1.id, rs1.step_number, rs0
from (
SELECT min(rs1.step_number) as min_sn, rs1.request_id as rid
FROM request_step rs1
where rs1.state = 'pending'
GROUP BY rs1.request_id
) rs0
left join request_step rs1 on rs1.step_number = rs0.min_sn and rs1.request_id = rs0.rid
order by rs1.request_id
答案 0 :(得分:1)
我认为您想看看lag()
:
select rs.*
from (select rs.*,
lag(state) over (partition by request_id order by step_number) as prev_state
from request_step rs
) rs
where state = 'pending' and
(prev_state is null or prev_state <> 'rejected');
编辑:
如果您要检查所有先前的步骤,则可以使用累计和执行类似的操作:
select rs.*
from (select rs.*,
lag(state) over (partition by request_id order by step_number) as prev_state,
sum(case when state = 'rejected' then 1 else 0 end) over (partition by request_id order by step_number) as num_rejects
from request_step rs
) rs
where state = 'pending' and
num_rejects = 0 and
(prev_status is null or prev_status <> 'pending');
答案 1 :(得分:0)
我认为这将为您提供所需的结果,而无需任何嵌套查询:
SELECT rs1.id, rs1.step_number, min(rs1.step_number) as min_sn, rs1.request_id as rid, rs1.*
FROM request_step rs1
LEFT OUTER JOIN request_step rs2
ON rs2.request_id=rs1.request_id AND rs2.state='rejected'
WHERE rs1.state = 'pending' AND rs2.id is null
GROUP BY rs1.request_id
我将保留对列的调整,以便仅在SELECT行上为您返回您想要的字段。