分组,顺序,分开

时间:2013-10-21 08:37:39

标签: sql-server-2008 tsql

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

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

实际上,以下查询几乎是我想要的,但是我希望看到Product而不是Price。

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

1 个答案:

答案 0 :(得分: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