在 SQL 中选择集合中的顶部项目

Selecting top item in set in SQL

我有一个 table,其中包含对象的位置、名称和价格。例如

Location | Name | Price
Store 1    Apple   $.50
Store 1    Pear    $.75
Store 2    Peach   $.75
Store 3    Mango   .50
Store 3    Melon   .00

我要返回的是

Location | Name | Price
Store 1    Apple   $.50
Store 2    Peach   $.75
Store 3    Mango   .50

我该怎么做?

row_subquery 中使用 groub by:

select location,name,price
from table_name
where (location,price) in
( select t.location,min(t.price)
  from table_name t
  group by t.location
)

您也可以使用 self join

select t1.location,t1.name,t1.price
from table_name t1 
join
( select location,min(price) as price
  from table_name 
  group by location
) t2 on t1.location=t2.location and t1.price=t2.price

使用以下 sql 查询。

Declare @table1 table(
Location varchar(256),
Name varchar(256),
Price varchar(256)
)

insert into @table1
select 'Store 1','Apple','$.50'
union select 'Store 1','Pear','$.75'
union select 'Store 2','Peach','$.75'
union select 'Store 3','Mango','.50'
union select 'Store 3','Melon','.00'

select * from @table1

select Location,Min(Name) as Name,Min(Price) as Price from 
@table1
group by Location