0

我有三列(交易者、产品、价格)的表格。我想让每个交易者获得一次,并以最高价格获得该交易者的产品。当我选择以下时,我看到重复的交易者:

select Trader, Product, Max(Price) as Price
from dbo.Sell
group by Trader, Product 
order by Max(Price) desc

上面的查询如何区分交易者?下面的查询不会改变任何东西:

select distinct Trader, Product, Max(Price) as Price
from dbo.Sell
group by Trader, Product 
order by Max(Price) desc

实际上,以下查询几乎是我想要的,但是我想查看产品而不是价格。

select Trader, Max(Price) as Price
from dbo.Sell
group by Trader
4

1 回答 1

1

试试这个查询,只有当交易者拥有多个具有最高价格的产品时,您才会获得多条记录。

;with cte as (
    select Trader, Max(Price) as Price
    from dbo.Sell
    group by Trader
)
select cte.Trader, s.Product, cte.Price
from cte join dbo.Sell s
         on cte.Trader = s.Trader and cte.Price = s.Price
order by cte.Price desc

第二种方法是使用一个rank()函数,但同样 rank() 函数将为相同的价格记录带来多个记录。

要获得单条记录,您可以使用Row_Number()代替Rank()

;with cte as (
    select Trader, Product, Price, 
         Rank() over (partition by Trader order by Price desc) rnk
    from dbo.Sell

)
Select Trader, Product, Price 
From cte
Where rnk = 1
Order by Price desc
于 2013-10-21T08:43:20.690 回答