gpt4 book ai didi

SQL检查组是否包含给定列的某些值(ORACLE)

转载 作者:行者123 更新时间:2023-12-05 08:27:11 25 4
gpt4 key购买 nike

我有包含这些记录的表 audit_log:

log_id | request_id | status_id
1 | 2 | 5
2 | 2 | 10
3 | 2 | 20
4 | 3 | 10
5 | 3 | 20

我想知道是否存在同时具有 status_id 5 和 10 的 request_id。因此,此查询应返回 request_id = 2,因为它的列 status_id 具有值 5 和 10(request_id 3 被省略,因为 status_id 列只有值 10 而没有 5)。
我如何使用 SQL 执行此操作?
我想我应该按 request_id 使用组,但我不知道如何检查组是否具有值为 5 和 10 的 status_id?

谢谢,
错误

最佳答案

这可能是一种方式:

/* input data */ 
with yourTable(log_id , request_id , status_id) as (
select 1 , 2 , 5 from dual union all
select 2 , 2 , 10 from dual union all
select 3 , 2 , 20 from dual union all
select 4 , 3 , 10 from dual union all
select 5 , 3 , 20 from dual
)
/* query */
select request_id
from yourTable
group by request_id
having count( distinct case when status_id in (5,10) then status_id end) = 2

工作原理:

select request_id, 
case when status_id in (5,10) then status_id end as checkColumn
from yourTable

给予

REQUEST_ID CHECKCOLUMN
---------- -----------
2 5
2 10
2
3 10
3

所以条件 count (distinct ...) = 2 完成了工作

关于SQL检查组是否包含给定列的某些值(ORACLE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44653833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com