tags:

views:

56

answers:

5

I have a table with card numbers and names. Some of those names are the same, meaning they have multiple cards. How can I select all the rows where the name occurs more than once?

A: 
select count(*) as n, [name]
from table1
group by [name]
having n > 1
Seva Alekseyev
SQL Server doesn't allow you to reference column aliases in the GROUP BY or HAVING clause - you'll get "Invalid column name 'n'", at least on SQL Server 2005.
OMG Ponies
+1  A: 

The following should work:

SELECT        * 
FROM cards    c1 
INNER JOIN    cards c2 on c1.name = c2.name 
WHERE         c2.id <> c1.id
Maxem
you'll get the results many times if ANY(select count(*) from cards group by name) > 2
Unreason
SELECT DISTINCT(c1.id) ... will make it work
Unreason
+2  A: 

Following may be the solution you are looking for

Select * from CardTable where cardid in ( select cardid from CardTable group by cardid having count(cardid) > 1)
Pranay Rana
The subquery is only necessary if you want to return columns other than the name.
OMG Ponies
-1: Your query does not work and will return no rows. count(cardid) = 1 if group by cardid, for all rows.
Unreason
i think you require to read question properly
Pranay Rana
@pranay: if you could explain why you think you query would return any rows (or where I am wrong) I'll be more than happy to correct my score. Do you consider cardid to be a name or id? Question states that there are card numbers and names.
Unreason
+1  A: 

Use:

  SELECT t.name
    FROM TABLE t
GROUP BY t.name
  HAVING COUNT(*) > 1
OMG Ponies
A: 

if you need the whole rows, here is a solution that will work on sql 7 and up

SELECT t1.* FROM(
 SELECT t.name
    FROM YourTable t
GROUP BY t.name
  HAVING COUNT(*) > 1) t2
  JOIN YourTable t1 on t2.name = t1.name
SQLMenace
Is the performance of this query as good as SELECT * FROM YourTable WHERE t.name IN (subquery) on MS SQL?
Unreason