搜索重复的行

时间:2016-03-22 10:36:12

标签: sql sql-server

我想检查表ParticipantsDebtor中是否有重复项,将重复项与名称,ParticipantsCodeDateOfBirth NameParticipantsCode字段进行比较在ParticipantsDebtor表中,DateOfBirthParticipantDebtorDetail表中,我的请求变成了我不知道这是否正确但是很长或者是假的

ParticipantsDebtor有:

  • DebtorId
  • 姓名
  • ParticipantsCode

ParticipantDebtorDetail有:

  • DebtorId
  • DATEOFBIRTH

查询:

SELECT a.ParticipantCode,
       a.Name,
       COUNT(a.DebtorId) AS DuplicateNumber,
       b.DateOfBirth
FROM ParticipantDebtors a WITH (NOLOCK),
     crem.ParticipantDebtorDetail b WITH (NOLOCK)
WHERE a.DebtorId <> b.DebtorId
GROUP BY a.ParticipantCode,
         a.Name,
         b.DateOfBirth
HAVING COUNT(a.DebtorId) > 1

1 个答案:

答案 0 :(得分:1)

不正确。您需要join个密钥。 。 。简单规则:从不FROM子句中使用逗号。 始终使用明确的JOIN语法:

SELECT d.ParticipantCode, d.Name, dd.DateOfBirth, COUNT(*) as NumDups
FROM ParticipantDebtors d with(nolock) JOIN
     crem.ParticipantDebtorDetail dd  with(nolock)
     ON d.DebtorId = dd.DebtorId
GROUP BY d.ParticipantCode, d.Name, dd.DateOfBirth
HAVING COUNT(*) > 1;

如果单个债务人可以多次出现在任一表格中,那么您可以将HAVING条件和NumDups的计算替换为:

HAVING COUNT(DISTINCT d.DebtorID) > 1