2013-07-30 44 views
2

假设你有一个表,如:如何在Oracle中查找相关值?

id foreign_key status 
------------------------ 
1 1   new 
2 1   incative 
3 1   approved 
4 2   new 
5 2   new 
6 2   approved 
7 3   new 
8 3   approved 
9 4   approved 

如何寻找到一个给定foreign_key只有一个记录在状态新和其他被批准,如在foreign_key 3病历?

+0

如果任何回答的DID回答你的问题,请将其标记为答案,以便它可以帮助其他人知道这个问题已经得到解答..好的 –

回答

3
select foreign_key from table 
group by foreign_key 
having 
    abs(1 - count(case status when 'new' then 1 end)) + 
    abs(count(1) - 1 - count(case status when 'approved' then 1 end)) = 0 
+0

不错,但是它找到了一个记录无效的情况。我只需要一个是新的,其他所有人都已经获得批准。 – Thomas

+0

@Thomas - [demo](http://sqlfiddle.com/#!4/d41d8/14971)。感谢Ramblin的Man为这个演示代码。 –

+0

对不起,叶戈尔,它的作品。我昨天肯定犯了错。你能向我解释一下这个代码吗,它非常漂亮,我很想理解它。 – Thomas

1

像这样的事情

Select * 
from 
(
    Select foreign_key 
    from table 
    where status = 'new' 
    group by foreign_key 
    having count(1) = 1 
) new_st 
inner join 
(
    Select foreign_key 
    from table 
    where status = 'approved' 
    group by foreign_key 
    having count(1) = (select count(1)-1 from table t1 where t1.foreign_key =foreign_key) 
) app_st 
on new_st.foreign_key = app_st.foreign_key 
1
SELECT * 
    FROM (SELECT id, foreign_key, status, 
       COUNT (DECODE (status, 'new', 1)) 
        OVER (PARTITION BY foreign_key) 
        new_count, 
       COUNT (DECODE (status, 'approved', 1)) 
        OVER (PARTITION BY foreign_key) 
        approved_count, 
       COUNT (status) OVER (PARTITION BY foreign_key) total_count 
      FROM mytable) 
WHERE new_count = 1 AND new_count + approved_count = total_count; 

我使用了3个不同的计数。一个算新的,一个算数核准,一个算数所有状态。最后只选择那些new_count = 1和new_count + approved_count等于total_count的记录。

演示here

编辑:可以添加approved_count > 0条件,以确保至少有一个批准状态。