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
2010-05-11 18:36:09
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
2010-05-11 18:39:31
+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
2010-05-11 18:36:21
+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
2010-05-11 18:36:34
The subquery is only necessary if you want to return columns other than the name.
OMG Ponies
2010-05-11 18:40:40
-1: Your query does not work and will return no rows. count(cardid) = 1 if group by cardid, for all rows.
Unreason
2010-05-11 19:06:13
@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
2010-05-11 19:14:54
+1
A:
Use:
SELECT t.name
FROM TABLE t
GROUP BY t.name
HAVING COUNT(*) > 1
OMG Ponies
2010-05-11 18:37:11
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
2010-05-11 18:39:53
Is the performance of this query as good as SELECT * FROM YourTable WHERE t.name IN (subquery) on MS SQL?
Unreason
2010-05-11 19:07:54