oracle 11g中的SQL语句

时间:2016-09-25 04:56:39

标签: sql oracle oracle11g

我有一个以下格式的表格:

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,因为他们有部门2和部门3的状态200和500以及部门1 200

2 个答案:

答案 0 :(得分:3)

您需要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 

答案 1 :(得分: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