SQL Server 2012 - 寻找具有差异的重复项

时间:2016-05-27 20:35:49

标签: sql-server

在SQL Server 2012中,我有一个这样的表:

Id  | AccountID  | Accession  | Status
----------------------------------------
1   | 1234567    | ABCD       | F
2   | 1234567    | ABCD       | F
3   | 2345678    | BCDE       | F
4   | 8765432    | BCDE       | F
5   | 3456789    | CDEF       | F
6   | 9876543    | CDEF       | A

我需要查找具有相同加入状态且状态为" F"但行不同AccountID的行。

我需要一个可以返回的查询:

Id  | AccountID  | Accession  | Status
----------------------------------------
3   | 2345678    | BCDE       | F
4   | 8765432    | BCDE       | F

1和2不会被返回,因为它们具有相同的AccountID。不会返回5和6,因为6上的状态是" A"而不是" F"。

4 个答案:

答案 0 :(得分:1)

你可以这样做。

;WITH NonDupAccountIDs AS
(
    SELECT AccountID,Accession, Status
    FROM MyTable
    WHERE Status = 'F'
    GROUP BY AccountID,Accession, Status
    HAVING COUNT(Id) = 1
)
,DupAccessions AS
(
    SELECT Accession
    FROM MyTable
    WHERE Status = 'F'
    GROUP BY Accession
    HAVING COUNT(AccountID) > 1
)
select a.AccountID, a.Accession, a.Status 
FROM NonDupAccountIDs a
INNER JOIN DupAccessions b
ON a.Accession = b.Accession

答案 1 :(得分:1)

另一种选择

Declare @Table table (id int,AccountID varchar(25),Accession varchar(25),Status varchar(25))
Insert into @Table (id  , AccountID  , Accession  , Status) values
(1, 1234567,'ABCD','F'),
(2, 1234567,'ABCD','F'),
(3, 2345678,'BCDE','F'),
(4, 8765432,'BCDE','F'),
(5, 3456789,'CDEF','F'),
(6, 9876543,'CDEF','A')

Select A.* 
 from  @Table A
 Join (
        Select Accession
         From @Table
         Where Status='F'
         Group By Accession
         Having Min(Accession)=Max(Accession)
            and count(Distinct AccountID)>1
      ) B on a.Accession=B.Accession

返回

id  AccountID   Accession   Status
3   2345678     BCDE        F
4   8765432     BCDE        F

答案 2 :(得分:0)

这也有效。如果有多组重复项,则只返回ID最高的一组。 Example

John Cappelletti也有一个很好的解决方案,如果存在任何不协调,他会返回所有重复的值。 Example

我必须添加更多数据才能看到会发生什么。您应该决定如何处理这些事件。

select 
max(ID) ID,AccountID, Accession
from p where Status = 'F'
group by AccountID, Accession
having 
(select count(Accession) from (select max(ID) ID,AccountID, Accession from p where Status = 'F' group by AccountID, Accession) f where f.accession = p.accession)>1
;

答案 3 :(得分:-1)

SELECT t2.Id, t1.AccountID, t1.Accession, t1.Status
FROM TABLE_NAME t2
INNER JOIN (
    SELECT AccountID, Accession, Status
    FROM TABLE_NAME
    GROUP BY Status, Accession, AccountID
) t1
ON t1.AccountID = t2.AccountID

可能需要玩这个,但应该让你亲近。请务必将TABLE_NAME替换为您的表格。