这个链接几乎是相同的问题,但已经有了一些答案!
以下是我模拟的表格:
declare @Borg table (
ID int,
Foo int,
Bar int,
Blagh int
)
insert into @Borg values (1,10,20,30)
insert into @Borg values (2,10,5,1)
insert into @Borg values (3,20,50,70)
insert into @Borg values (4,20,75,12)
那么你可以进行匿名内连接来获取所需的数据。
select B.* from @Borg B inner join
(
select Foo,
MIN(Bar) MinBar
from @Borg
group by Foo
) FO
on FO.Foo = B.Foo and FO.MinBar = B.Bar
编辑Adam Robinson 指出,“此解决方案有可能在 Bar 的最小值重复时返回多行,并且会消除任何值为null
的foo”
根据您的用例,当 Bar 重复时具有重复值可能是有效的-如果您想找到所有 Bar 最小的 Borg 值,则同时拥有两个结果似乎是正确的方法。
如果您需要捕获在聚合字段中的NULLs
(在此情况下通过MIN聚合),则可以将 NULL 与可接受的高(或低)值进行coalesce
(这是一种hack):
...
MIN(coalesce(Bar,1000000)) MinBar -- A suitably high value if you want to exclude this row, make it suitably low to include
...
或者你可以使用UNION将所有这样的值附加到结果集的底部。
on FO.Foo = B.Foo and FO.MinBar = B.Bar
union select * from @Borg where Bar is NULL
由于不知道如何在相同的Foo
值之间进行选择,因此后者将不会将@Borg中具有相同Foo
值的值分组。