我在我的选择声明中也需要卖家ID,以便他们拥有最低价格和最高价格。以下是查询;请告诉我们需要做哪些更改?
Select count(Id) TotalSeller,
min(price) as MinPrice, ***SellerID_for_min_price***,
max(price) as MaxPrice, ***SellerID_for_max_price***
from ProdPrice
where prodPriceId=1212
数据:
ProdId SellerID Price
1212 65 34740
1212 20 34855
1212 88 37299
1212 69 38490
1212 108 39990
1212 35 39999
1212 96 40990
答案 0 :(得分:0)
要执行此类查询,您希望使用row_number()
来标识具有最小值和最大值的行:
Select count(Id) TotalSeller, min(price) as MinPrice,
min(case when seqnum_min = 1 then id end) as SellerIdMin,
max(price),
min(case when seqnum_max = 1 then id end) as SellerIdMax
from (select pp.*,
row_number() over (partition by prodPriceId order by price) as seqnum_min,
row_number() over (partition by prodPriceId order by price desc) as seqnum_max
from ProdPrice pp
where prodPriceId=1212
) pp
要获取名称,可以在子查询中进行连接:
Select count(Id) TotalSeller, min(price) as MinPrice,
min(case when seqnum_min = 1 then SellerName end) as SellerNameMin,
max(price),
min(case when seqnum_max = 1 then SellerName end) as SellerNameMax
from (select pp.*, s.SellerName,
row_number() over (partition by prodPriceId order by price) as seqnum_min,
row_number() over (partition by prodPriceId order by price desc) as seqnum_max
from ProdPrice pp join
Sellers s
on pp.id = s.id
where prodPriceId=1212
) pp