Domanda

I have a SQL query such as the following:

SELECT field1, field2, field3, field4, field5
FROM tablename
WHERE field1 = condition
GROUP BY 1,2,3,4,5
HAVING COUNT(field1) > 2

I expected the query to return only the results which have more than 2 rows in the resultset, however the query returns 0 zero.

Could anyone point out what I'm doing wrong? I need to keep my query selecting the fields it has been, but limit the results coming back to only those who have at least 2 rows. If they only have 1, I don't want them included in my results.

È stato utile?

Soluzione 2

I suspect (although from my comment under the question I am not sure) that you want

SELECT field1, field2, field3, field4, field5
FROM tablename 
WHERE field1 = condition
  AND field1 IN 
       (SELECT field1
        FROM tablename 
        GROUP BY 1
        HAVING COUNT(field1) >=2 );

Altri suggerimenti

The where clause specifies that field1 has to be equal to condition.

count(field1) would essentially always be 1 (distinct values of field1 would be 1 and equal to condition).

That's why we always have 0 results since the count is never > 2.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top