Say I have this table:create table min_test ( a int not null, b int not null, c int not null, d varchar(20), constraint pk_min_test primary key (a,b,c))
And I populate it with this data:insert min_test (a,b,c,d)select 1,1,2,'this one'union select 1,1,3,'not this one'union select 1,2,1,'not this one'union select 1,2,2,'not this one'union select 2,4,7,'not this one'union select 2,3,4,'this one'union select 3,10,10,'this one'
I need to query for a single d value for each a with the following business rule: If there are multiple d's for each a, use the row with the lowest b. If there are still multiples, use the lowest c for the lowest b. {a,b,c} is unique (primary key).So the expected rowset should look like:a d ----------- -------------------- 1 this one2 this one3 this one(3 row(s) affected)
So far, I have come up with this query:select m.a, m.dfrom min_test m inner join ( select m.a, m.b, min(c) as c from min_test m inner join ( select a, min(b) as b from min_test group by a) b on m.a = b.a and m.b = b.b group by m.a, m.b) c on m.a = c.a and m.b = c.b and m.c = c.c
Can anyone come up with a better performer?Thanks in advance.Jay White{0}