查找组中存在两个条件的位置

时间:2018-07-11 20:56:10

标签: sql database postgresql

我有一张桌子:

ref | name
===========
123abc | received
123abc | pending
134b   | pending
156c   | received

我希望能够识别ref仅具有pending而没有received的实例。请注意,同一引用可能有多个receivepending

如何输出仅具有待处理而不是未接收的引用?

因此在我的示例中,它将返回:

134b | pending

我认为是这样的:

SELECT ref, name FROM my_table
WHERE ref IS NOT NULL
GROUP BY ref, name
HAVING ref = 'pending' AND ref = 'received'
;

3 个答案:

答案 0 :(得分:1)

我将使用聚合:

select name
from my_table
where ref in ('pending', 'received')
group by name
having min(ref) = 'pending' and min(ref) = max(ref);

严格来说,不需要比较第二个条件的最小值和最大值。但这消除了对值的字母顺序的依赖。

答案 1 :(得分:1)

您可以根据需要使用不存在(顺便说一句,从您的数据中,“名称”列包含诸如待处理和已接收的值)

select distinct ref, name
from my_table t1
where t1.name = 'pending' and not exists (select * from my_table t2 where t1.ref=t2.ref and t2.name='received')

PS。您可以在此处使用示例数据和我的查询进行验证: Hash#dig

答案 2 :(得分:1)

另一种实现方法是使用WITH语句。这样,就不需要嵌套的子查询。

WITH ref_recieved_pending AS (
    SELECT
      ref,
      sum(CASE WHEN name = 'received'
        THEN 1
          ELSE 0 END) as recieved_count,
      sum(CASE WHEN name = 'pending'
        THEN 1
          ELSE 0 END) as pending_count
    FROM test_table_2
    GROUP BY ref
)
SELECT DISTINCT
  ref,
  'pending' as pending
FROM ref_recieved_pending
WHERE pending_count > 0 AND recieved_count = 0;
相关问题