繁体   English   中英

选择SQL集中的顶级项目

[英]Selecting top item in set in SQL

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

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

我要退货的是

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

我怎样才能做到这一点?

使用groub byrow_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
)

您也可以使用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','$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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