SQL检查组是否包含给定列(ORACLE)的某些值
我有带有以下记录的表审核日志:SQL检查组是否包含给定列(ORACLE)的某些值,sql,oracle,group-by,Sql,Oracle,Group By,我有带有以下记录的表审核日志: log_id | request_id | status_id 1 | 2 | 5 2 | 2 | 10 3 | 2 | 20 4 | 3 | 10 5 | 3 | 20 我想知道是否同时存在状态为5和10的请求id。因此,此查询应返回request_id=2,因为其列status_id的值为5和10(reques
log_id | request_id | status_id
1 | 2 | 5
2 | 2 | 10
3 | 2 | 20
4 | 3 | 10
5 | 3 | 20
我想知道是否同时存在状态为5和10的请求id。因此,此查询应返回request_id=2,因为其列status_id的值为5和10(request_id 3被省略,因为status_id列只有10而没有5)。如何使用SQL实现这一点?
我想我应该按请求使用group\u id,但我不知道如何检查group是否具有值为5和10的status\u 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
给予
因此,条件count(distinct…=2
起作用这应该起作用:
SELECT request_id
FROM table_name
GROUP BY request_id
HAVING COUNT( CASE status_id WHEN 5 THEN 1 END ) > 0
AND COUNT( CASE status_id WHEN 10 THEN 1 END ) > 0
select
log5.*, log10.status_id
from
audit_log log5
join audit_log log10 on log10.request_id = log5.request_id
where
log5.status_id = 5
and log10.status_id = 10
order by
log5.request_id
;
以下是输出:
+ ----------- + --------------- + -------------- + -------------- +
| log_id | request_id | status_id | status_id |
+ ----------- + --------------- + -------------- + -------------- +
| 1 | 2 | 5 | 10 |
+ ----------- + --------------- + -------------- + -------------- +
1 rows
下面是设置示例的sql:
create table audit_log (
log_id int,
request_id int,
status_id int
);
insert into audit_log values (1,2,5);
insert into audit_log values (2,2,10);
insert into audit_log values (3,2,20);
insert into audit_log values (4,3,10);
insert into audit_log values (5,3,20);
要检查这两个值是否存在(不考虑其他值),可以在聚合之前进行筛选:
select request_id
from yourTable
where status_id in (5,10)
group by request_id
having count(*) = 2 -- status_id is unique
-- or
having count(distinct status_id) = 2 -- status_id exists multiple times
你可以使用。我正在使用Oralce db…组合
request\u id/status\u id
唯一吗?经过大量搜索,你救了我的命!非常感谢。
select request_id
from yourTable
where status_id in (5,10)
group by request_id
having count(*) = 2 -- status_id is unique
-- or
having count(distinct status_id) = 2 -- status_id exists multiple times