Question

Let's say I have table of number pairs:

a | b
--+--
1 | 1
2 | 1
3 | 1
2 | 2
4 | 2
5 | 5
1 | 3

For each b I want to pick an a such as there are no 2 identical as for different bs.

If I do a simple query with group by:

select * from t group by b

I get the following results back:

a | b
--+--
1 | 1
2 | 2
5 | 5
1 | 3

a == 1 for b == 1 and b == 3

What I want instead is something like this:

a | b
--+--
3 | 1
2 | 2
5 | 5
1 | 3

Could you help me with this problem? I assume that there's a known terminology for this kind of subset querying, but I'm not aware of it, and that makes searching for answers harder.

Bonus points if the query picks largest a for given b while keeping the given uniqueness constraint. For my example the result would be:

a | b
--+--
3 | 1
4 | 2
5 | 5
1 | 3
Was it helpful?

Solution

I think the first approach will be:

select MAX(a) as a,
       b
from t as t1
where NOT EXISTS(select a from t where b<>t1.b and a=t1.a)
      or 
      NOT EXISTS(select a from t where a in (select a from t where b=t1.b)
                 GROUP BY a 
                 HAVING COUNT(*)=1)

GROUP BY b

SQLFiddle demo

We should group by b and find MAX(a) but from the special subrange of the main table. First we should get all a which aren't exist for another b (it is the first condition). But in the case of b=3 we get the case that ALL a exist for other b so the second condition handles this case.

OTHER TIPS

try this

select max(a),b from t group by b;

Try

 SELECT MAX(`a`) as `a`, `b` FROM Table1 GROUP BY `b`

demo at http://sqlfiddle.com/#!2/f4897/8

Please check this, I have not verified:-

SELECT max(a) AS a, b FROM t WHERE  GROUP BY b 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top