简体   繁体   中英

Combination of group by, order and distinct

My query

 SELECT a, b, c
 FROM table
 WHERE
    a > 0 AND a < 4 AND
    b IN (
        SELECT z FROM table2
        WHERE x = y
    )

produces the following output:

A B C
1 1 Car
1 1 Keyboard
1 2 Apple
1 3 Frog
2 1 Carrot
2 2 Parrot
3 1 Doll

what I want is the following output

A B C
1 1 Car
2 1 Carrot
3 1 Doll

So basically for every A, the lowest B and associated C (as well as other columns).

I tried various join types, group bys, but I am running out of ideas.

How can I accomplish this?

Do a join on a subquery:

 SELECT a, b, c
 FROM table t1
 INNER JOIN (SELECT a a2, MIN(b) b2 FROM table GROUP BY a) t2
     ON t1.a = t2.a2 AND t1.b = t2.b2
 WHERE
    a > 0 AND a < 4 AND
    b IN (
        SELECT z FROM table2
        WHERE x = y
    )   

Use a Top N Apply

SELECT a, b, c
 FROM table
 CROSS APPLY (SELECT top 1 z 
                FROM table2
                WHERE x = y
                order by z ) t2
 WHERE a > 0 AND a < 4 AND

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM