2

Say you have a table such as:

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

How to find records where the for a given foreign_key there is only one record in status new and the other are approved, like in case of foreign_key 3?

4

3 回答 3

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
于 2013-07-30T14:02:26.723 回答
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 的记录。

演示在这里

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

于 2013-07-30T15:32:32.870 回答
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
于 2013-07-30T14:04:31.483 回答