views:

73

answers:

2

I am trying to develop a query to insert unique records but am receiving the SQL Server Primary Key error for trying to insert duplicate records. I was able to insert some values with this query but not for this record (score_14).

So now I am trying to find duplicate record with the following query. The challenge is that my PK is based on 3 columns: StudentID, MeasureDate, and MeasureID--all from a different table not mentioned below.

But this only shows me count--instead I want to just return records with count > 1. How do I do that?

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
+1  A: 

you need to take A.score_14 out of your group by clause if you want to count it

Beth
+2  A: 

Beth is correct - here's my re-write of your query:

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

Previously:

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
OMG Ponies
Thank you guys! This query worked--I think. But the problem is that your query returns 0 records! (For Count > 1). Why would this be? Cause when I try to insert my Select statement, I get the error:Msg 2627, Level 14, State 1, Line 1Violation of PRIMARY KEY constraint 'PK_j5c_MasterMeasures'. Cannot insert duplicate key in object 'dbo.j5c_MasterMeasures'.The statement has been terminated.
salvationishere
@salvationishere: Having re-read the question - you couldn't apply the primary key constraint if there was duplicate data in place. You'd have to fix the data before you could... so the issue is you're attempting to insert duplicate data, not that it exists.
OMG Ponies
Thanks so much for your helps! It looks like the problem was the PK.
salvationishere