2

次のようなテーブルがあるとします。

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の場合のように、ステータスがnewのレコードが1つしかなく、もう1つのレコードが承認されているレコードを見つける方法は?

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 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 に答える
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つの異なるカウントを使用しました。1 つは新規をカウントし、1 つは承認済みをカウントし、もう 1 つはすべてのステータスをカウントします。最後に、new_count = 1 で、new_count + approval_count が total_count に等しいレコードのみを選択します。

ここでデモ。

編集:approved_count > 0少なくとも1つの承認済みステータスがあることを確認する条件を追加できます。

于 2013-07-30T15:32:32.870 に答える