查询以选择销售额最高的产品

时间:2018-10-18 10:26:36

标签: ssms sql-server-2014

我想从某些数据中获得现金销售最高的产品的产品ID,产品名称和现金销售。

我知道如何编写查询以提取所有记录,然后按顺序排列它们,其中现金销售最高(在下面)。

然后,我可以从该查询中选择销售额最高的记录。

但是有没有更快的方法来写这个?即一个简单的查询,它只会返回销售最高的记录? TIA。

select
    es.ClientProductID,
    es.ProductName,
    ash.price * ash.sales as CashSales 
from AggregatedSalesHistory as ash 
join v_EnterpriseStructure as es on es.ProductSID = ash.ProductSID 
group by 
    es.ClientProductID,
    es.ProductName,
    ash.price * ash.sales 
order by 
    ash.price * ash.sales DESC

2 个答案:

答案 0 :(得分:0)

select
    es.ClientProductID,
    es.ProductName,
    ash.price * ash.sales as CashSales 
from AggregatedSalesHistory as ash 
join v_EnterpriseStructure as es on es.ProductSID = ash.ProductSID 
group by 
    es.ClientProductID,
    es.ProductName,
    ash.price * ash.sales 
having
    max(ash.price * ash.sales)

以上查询将为您带来最高销售额的结果。

答案 1 :(得分:0)

您可以对结果集使用排名和分组来获得第一名(或任何其他排名)的行

select * from (select
row_number() over (partition by es.ClientProductID,es.ProductName order by (ash.price * ash.sales) desc) as salesRank,
    es.ClientProductID a,
    es.ProductName b,
    ash.price * ash.sales as CashSales 
from AggregatedSalesHistory as ash 
join v_EnterpriseStructure as es on es.ProductSID = ash.ProductSID ) subquery1 where salesRank=1;
相关问题