views:

64

answers:

2

I'm trying to select duplicates from this table:

snr zip
01 83
02 82
03 43
04 28

Expected result is just empty table. Cuz it got no duplicates.

I've tried with this query:

SELECT snr, zip
FROM student
GRUOP BY snr
HAVING  (COUNT(zip) > 1)

But it says that syntax is error, and that I'm trying to query an aggregate functions, etc..

+6  A: 

It looks like you need to either remove zip from the SELECT columns, or else wrap it in an aggregate function, such as COUNT(zip):

SELECT   snr, COUNT(zip)
FROM     student
GROUP BY snr
HAVING   (COUNT(zip) > 1)

Also check out @OMG Ponies's answer for further suggestions.

Daniel Vassallo
+1 - Also OP misspelled GROUP which could cause an issue.
JNK
Thank you. I used this one and it works.
jdnhldn
+1: You were first, but we were slightly different.
OMG Ponies
@OMG Ponies: Thanks... If you ever change your display name on Stack Overflow, my references to your answers will really look freaky (funny)! :)
Daniel Vassallo
Any time someone quotes my display name, it's hilarious to read out loud. It's like reading something from an author with Tourette's, just less vulgar :)
OMG Ponies
@OMG: lol... true! :)
Daniel Vassallo
+5  A: 

Use:

  SELECT snr, zip
    FROM student
GROUP BY snr, zip
  HAVING COUNT(DISTINCT zip) > 1

Standard SQL requires that columns in the SELECT clause that are not wrapped in aggregate functions (COUNT, MIN, MAX, etc) need to be defined in the GROUP BY. However, MySQL and SQLite allow for columns to be omitted.

Additionally, use COUNT(DISTINCT or you'll risk false positives.

OMG Ponies
On having, You have missed a brackets. Should it be like: HAVING (COUNT(DISTINCT zip) > 1)?
jdnhldn
@jdnhldn: Thx - corrected the typo. But no - you don't need to enclose anything in the HAVING clause within brackets. The HAVING clause is like the WHERE clause - only difference is you can't use aggregate functions in the WHERE, which is why you use them in the HAVING.
OMG Ponies
@OMG Ponies, IMO the distinct is not necessary, if you have already counted zip on select and Having like: SELECT snr, COUNT(zip)FROM studentGROUP BY snrHAVING (COUNT(zip) > 1)Am I wrong?
jdnhldn
@jdnhldn: It depends on your data, and what you want to get out of it - the original implied that you wanted to see the zip value that was duplicated. There's possibly duplicates of the snr value, I'd expect to see nearly (if not all) snr values returned by your query.
OMG Ponies