【问题标题】:How to find duplicate records in SQL?如何在 SQL 中查找重复记录?
【发布时间】:2010-08-21 05:51:10
【问题描述】:

我正在尝试开发一个查询来插入唯一记录,但由于尝试插入重复记录而收到 SQL Server 主键错误。我能够使用此查询插入一些值,但不能插入此记录(score_14)。

所以现在我正在尝试使用以下查询查找重复记录。挑战在于我的 PK 基于 3 列:StudentID、MeasureDate 和 MeasureID——全部来自下面未提及的不同表。

但这只会显示计数——而不是我只想返回计数 > 1 的记录。我该怎么做?

select count(a.score_14) as score_count, A.studentid, A.measuredate, B.measurename+' ' +B.LabelName 
from [J5C_Measures_Sys] A
join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID 
join sysobjects so on so.name = 'J5C_Measures_Sys' 
join syscolumns sc on so.id = sc.id 
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
where so.type = 'u' and sc.name = 'score_14' and a.score_14 is not null 
AND A.STUDENTID IS NOT NULL AND A.MEASUREDATE IS NOT NULL AND B.MEASURENAME IS NOT NULL
--and count(a.score_14)>1
group by a.studentid, a.measuredate, B.measurename, B.LabelName, A.score_14
having count(a.score_14) > 1

【问题讨论】:

    标签: sql sql-server tsql sql-server-2008 duplicates


    【解决方案1】:

    Beth 是正确的 - 这是我对您的查询的重写:

    SELECT a.studentid, a.measuredate, a.measureid
      from [J5C_Measures_Sys] A
    GROUP BY a.studentid, a.measuredate, a.measureid
      HAVING COUNT(*) > 1
    

    以前:

    SELECT a.studentid, a.measuredate, a.measureid
      from [J5C_Measures_Sys] A
      join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID 
      join sysobjects so on so.name = 'J5C_Measures_Sys'
                        AND so.type = 'u'
      join syscolumns sc on so.id = sc.id 
                        and sc.name = 'score_14' 
      join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
     where a.score_14 is not null  
       AND B.MEASURENAME IS NOT NULL
    GROUP BY a.studentid, a.measuredate, a.measureid
      HAVING COUNT(*) > 1
    

    【讨论】:

    • 谢谢你们!这个查询有效——我想。但问题是您的查询返回 0 条记录! (对于计数 > 1)。为什么会这样?因为当我尝试插入我的 Select 语句时,我收到错误消息:Msg 2627, Level 14, State 1, Line 1 Violation of PRIMARY KEY constraint 'PK_j5c_MasterMeasures'。无法在对象“dbo.j5c_MasterMeasures”中插入重复键。声明已终止。
    • @salvationishere:重新阅读问题后 - 如果存在重复数据,您将无法应用主键约束。您必须先修复数据...所以问题是您尝试插入重复数据,而不是它存在。
    • 非常感谢您的帮助!看来问题出在PK上。
    【解决方案2】:

    如果你想计算它,你需要把 A.score_14 从你的 group by 子句中去掉

    【讨论】:

      猜你喜欢
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 2019-08-06
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      • 2010-10-25
      相关资源
      最近更新 更多