假设您有一个表格,如:
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只有一个记录处于状态new而另一个记录被批准,就像foreign_key 3一样?
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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
条件,以确保至少有一个已批准的状态。