查找重复记录

Finding duplicate records

Table如下:

Request#  type  status
123         R     partially complete 
123         S     complete
345         S     partially complete
345         S     complete

R代表短请求,S代表长请求。当状态为 "complete" 时,每个请求类型都变为 S。我需要找到已完成的所有 "R" 类型的请求

select * 
from table 
where type ='R' and status='partially complete' OR 
      type ='s' and status='complete'

预期结果

Request#  type  
123         R

我想你想要这个

select Request#, min(type) as type
  from "table" 
 group by Request#
 having min(status)='complete'

一种简单的方法是使用聚合:

SELECT
    request
FROM yourTable
GROUP BY
    request
HAVING
    COUNT(CASE WHEN type = 'R' AND status = 'partially complete' THEN 1 END) > 0 AND
    COUNT(CASE WHEN type = 'S' AND status = 'complete' THEN 1 END) > 0;

我们也可以使用自连接来表达:

SELECT DISTINCT t1.request
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.request = t2.request AND
       t2.type = 'S' AND t2.status = 'complete'
WHERE
    t1.type = 'R' AND
    t1.status = 'partially complete';

这是 Barbaros 解决方案的概括:

select Request#
from "table" 
group by Request#
having sum(case when status = 'complete' then 1 else 0 end) > 0 and
       sum(case when type = 'R' then 1 else 0 end) > 0;