Finding unequal associated values

时间:2017-08-05 10:23:37

标签: sql

+------+------+
| ColA | ColB |
+------+------+
| dog  |   74 |
| dog  |   74 |
| dog  |   74 |
| cat  |   55 |
| cat  |   55 |
| cat  |   55 |
| bird |   44 |
| bird |   43 |
| bird |   44 |
+------+------+

In the above table.

  • All values (74) are the same, and are associated to "dog".
  • The same applies to "cat", all values (55), are the same, and are associated to "cat".
  • However with "bird", notice that not all values are the same, since there's a 44 and a 43 associated to "bird".

So how can I write out my SQL query, to return all animals, whose associated values aren't all the same, which would be "bird" in this case.

Thank you in advance

3 个答案:

答案 0 :(得分:1)

You can do GROUP BY twice, and filter in the HAVING clause:

SELECT g.ColA
FROM (
    SELECT a.ColA, a.ColB
    FROM Animals a
    GROUP BY a.ColA, a.ColB
) g
GROUP BY g.ColA
HAVING COUNT(*) > 1

Inner GROUP BY will produce one row for each distinct {ColA;ColB} pair; the outer GROUP BY with HAVING will reject ColAs with a single associated ColB.

答案 1 :(得分:0)

I would do this with GROUP BY and HAVING, but no subquery is necessary:

select colA
from t
group by colA
having min(colB) <> max(colB);

This simply returns the colA values whose min and max colB values are different.

答案 2 :(得分:0)

select colA
from t
group by colA
having count(distinct colB) <> 1;

与戈登相似,但目的可能更明显一点。