我希望通过' location&amp ;;来选择最畅销的销售人员。产品'组合。 第一批我和排序排名,然后我总结为"位置&产品",然后我想放弃除了顶级销售人员之外的所有"位置&产物"这样查询结果只包含顶级销售人员的位置&位置&产物"每个"位置&的总销售额产物"组合
我不具备的一部分是"选择Rank = 1" - 添加"其中" "来自"不起作用:
Select Location, Product, Sales, Salesperson
row_number() OVER (PARTITION BY concat(Location,Product) ORDER BY Sales desc) AS Rank,
Sum(Sales) OVER(PARTITION BY concat(Location,Product)) AS Salesbylocprod
From Table A
答案 0 :(得分:0)
您可以使用子查询。此外,您不需要连接partition by
:
Select Location, Product, Sales, Salesperson, Salesbylocprod
from (select a.*
row_number() over (partition by Location, Product order by Sales desc) as seqnum,
sum(Sales) over (partition by Location, Product) as Salesbylocprod
From Table A
) a
where seqnum = 1;
请注意,我已将列的名称从rank
更改为seqnum
。 rank
有点暗示它是使用rank()
函数计算的。这与row_number()
不同,因此该名称具有误导性。
答案 1 :(得分:0)
您还可以使用公用表格表达式:
;WITH CTE
AS (SELECT *,
ROW_NUMBER() OVER(PARTITION BY Location,Product ORDER BY Sales DESC) AS RowNum,
SUM(Sales) OVER(PARTITION BY Location,Product) AS SalesByLocProd
FROM TableA
)
SELECT Location,
Product,
Sales,
SalesPerson,
SalesByLocProd
FROM CTE
WHERE RowNum = 1;