+------+------+
| ColA | ColB |
+------+------+
| dog | 74 |
| dog | 74 |
| dog | 74 |
| cat | 55 |
| cat | 55 |
| cat | 55 |
| bird | 44 |
| bird | 43 |
| bird | 44 |
+------+------+
In the above table.
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
答案 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 ColA
s 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;
与戈登相似,但目的可能更明显一点。