views:

45

answers:

2

I have a SQL Query giving me a list of double records in my database.

select periodid, itemid from periodscore  
group by periodid, itemid
having count(*) > 1

This works as expected, but now I would like to retrieve additional fields of these records (such as date last updated etc). So I tried:

select * from periodscore where periodscoreid in
(select periodscoreid from periodscore  
group by periodid, itemid
having count(*) > 1)

Of course this doesn't work and gives me the error:

Column 'periodscore.PeriodScoreID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

How can I retrieve the extra fields in this query?

+2  A: 
select ps.* 
from periodscore ps
inner join (
    select periodid, itemid 
    from periodscore   
    group by periodid, itemid 
    having count(*) > 1
) psm on ps.periodid = psm.periodid and ps.itemid = psm.itemid
RedFilter
Thanks for the fast answer! This query as well gives me 216 records as opposed to the original 103
Sam
@Sam - The first query tells you the groups. This gives you the rows belonging to those groups. Of course all of the groups will have at least 2 rows as that is the purpose of the query! If you only want one row per group returned then which one?
Martin Smith
Hm, good point :) Thanks for the answer!
Sam
@Martin, Some rows duplicated more than two times, for getting exactly 206 rows should be used condition count(*) = 2
Michael Pakhantsov
+1  A: 
  select p1.* from periodscore p1 JOIN 
  (select periodid, itemid from periodscore  
   group by periodid, itemid
   having count(*) > 1) p2
   ON (p1.periodId = p2.periodId
       AND p1.itemid = p2.itemid)

if periodid or item have null values then

  select p1.* from periodscore p1 JOIN 
  (select periodid, itemid from periodscore  
   group by periodid, itemid
   having count(*) > 1) p2
   ON (IFNULL(p1.periodId,0) = IFNULL(p2.periodId,0))
       AND IFNULL(p1.itemid,0) = IFNULL(p2.itemid,0))
Michael Pakhantsov
Thanks for the fast answer! However, this query seems to give me about the double number of records I get from the original one... Original one gave me 103 records, this one 216...
Sam
@Same, Added IFNULL for cases when periodid or itemid is null
Michael Pakhantsov
I'm guessing you meant ISNULL? The ids are actually uniqueidentifiers, but you had no way of knowing that.
Sam
@Sam, You had rows which duplicated more than 2 times :)
Michael Pakhantsov