簡體   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