Tuesday, June 1, 2010

SQL group count with conditions

If you have a table like this :
CREATE TABLE data { id INTEGER , type INTEGER }

You can list the times that each id appears in the table with the following query :
SELECT id , count( type ) FROM data GROUP BY id

Now, if you want to list the same data but adding some condition, like list only the elements that appears more than one time, then you can perform that with the help of some aliases and nested query :
SELECT d.id , d.c FROM (SELECT id , count( type ) as c FROM data GROUP BY id ) d WHERE d.c > 1


This work in MySQL

No comments:

Post a Comment