我的查询
SELECT a, b, c
FROM table
WHERE
a > 0 AND a < 4 AND
b IN (
SELECT z FROM table2
WHERE x = y
)
产生以下输出:
A B C
1 1 Car
1 1 Keyboard
1 2 Apple
1 3 Frog
2 1 Carrot
2 2 Parrot
3 1 Doll
我想要的是以下输出
A B C
1 1 Car
2 1 Carrot
3 1 Doll
所以基本上每个A,最低的B和相关的C(以及其他列)。
我尝试了各种联接类型,分组,但我的想法已经用完了。
我该如何做到这一点?
答案 0 :(得分:0)
在子查询上进行连接:
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
)
答案 1 :(得分:0)
使用前N个
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