繁体   English   中英

Oracle 11g中的SQL语句

[英]SQL statement in oracle 11g

我有以下格式的表格:

ID      code   status
-----   -----  ------
1       Dept1    200
1       Dept2    500
1       Dept3    500
1       Dept3    200
2       Dept1    200
2       Dept2    500
2       Dept3    500
2       Dept3    500       
3       Dept1    200
3       Dept2    500
3       Dept3    500
3       Dept2    200
4       Dept1    500
4       Dept2    500
4       Dept3    500

我需要的输出是ID 1和ID 3

任何人都可以帮我编写将打印ID 1和ID 3的SQL,因为它们的状态分别为200和500以及部门2和部门3和部门1 200

您需要Conditional Aggregation

根据您的解释,仅ID = 3满足所有条件

SELECT id 
FROM   Yourtable
GROUP  BY id 
HAVING Count(CASE WHEN "code" = 'Dept2' AND "status" = 200 THEN 1 END) = 1 
       AND Count(CASE WHEN "code" = 'Dept3' AND "status" = 500 THEN 1 END) = 1 
       AND Count(CASE WHEN "code" = 'Dept1' AND "status" = 200 THEN 1 END) = 1 

您的要求是查找ID与codestatus五个组合匹配的记录。 一种满足此要求的简单方法是将每个组合指定为单独的子查询,并使用INTERSECT集合运算符将结果简化为唯一的ID:

select id from your_table
where code = 'Dept1' and status = 200
intersect
select id from your_table
where code = 'Dept2' and status = 200
intersect
select id from your_table
where code = 'Dept2' and status = 500
intersect
select id from your_table
where code = 'Dept3' and status = 200
intersect
select id from your_table
where code = 'Dept3' and status = 500

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM