简体   繁体   中英

Selecting top item in set in SQL

I have a single table that has a location, name, and price of objects. For example

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

What I want returned is

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

How can I do this?

use groub by within row_subquery :

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
)

you can also use a 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

use following sql query.

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','$1.50'
union select 'Store 3','Melon','$2.00'

select * from @table1

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

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