如何查看每个员工在哪个类别中销售的商品最多?我只能显示员工姓名和已售出的商品
How to check in which category each employee has sold the most goods? I can display only employee's name and sold goods
整个table
USE Northwind
SELECT MAX(TotalOrder)
FROM vwEmployesAndMostSoldCategories
GROUP MAX(TotalOrder)
我只能输出什么
USE Northwind
SELECT
FullName
, MAX(TotalOrder) AS TheMaxSoldUnits
FROM vwEmployesAndMostSoldCategories
GROUP BY FullName
您可以在此处使用 TOP
查询:
WITH cte AS (
SELECT FullName, CatgegoryName,
SUM(TotalOrder) AS SumTotalOrder,
ROW_NUMBER() OVER (PARTITION BY FullName
ORDER BY SUM(TotalOrder) DESC) rn
FROM vwEmployesAndMostSoldCategories
GROUP BY FullName, CategoryName
)
SELECT FullName, CategoryName, SumTotalOrder AS TotalOrder
FROM cte
WHERE rn = 1;
如果给定的员工可能 并列 因为有两个或更多类别的订单总数相同,而您想要显示所有并列,则替换 ROW_NUMBER
, RANK
.
如果我没听错,你可以使用 with ties
:
select top (1) with ties e.*
from vwEmployesAndMostSoldCategories e
order by rank() over(partition by fullname order by totalorders desc)
对于每位员工,此 returns 具有最大 totalorders
的行(如果存在最高关联,则返回同一员工的所有关联行)。看来你不需要在这里聚合。
整个table
USE Northwind
SELECT MAX(TotalOrder)
FROM vwEmployesAndMostSoldCategories
GROUP MAX(TotalOrder)
我只能输出什么
USE Northwind
SELECT
FullName
, MAX(TotalOrder) AS TheMaxSoldUnits
FROM vwEmployesAndMostSoldCategories
GROUP BY FullName
您可以在此处使用 TOP
查询:
WITH cte AS (
SELECT FullName, CatgegoryName,
SUM(TotalOrder) AS SumTotalOrder,
ROW_NUMBER() OVER (PARTITION BY FullName
ORDER BY SUM(TotalOrder) DESC) rn
FROM vwEmployesAndMostSoldCategories
GROUP BY FullName, CategoryName
)
SELECT FullName, CategoryName, SumTotalOrder AS TotalOrder
FROM cte
WHERE rn = 1;
如果给定的员工可能 并列 因为有两个或更多类别的订单总数相同,而您想要显示所有并列,则替换 ROW_NUMBER
, RANK
.
如果我没听错,你可以使用 with ties
:
select top (1) with ties e.*
from vwEmployesAndMostSoldCategories e
order by rank() over(partition by fullname order by totalorders desc)
对于每位员工,此 returns 具有最大 totalorders
的行(如果存在最高关联,则返回同一员工的所有关联行)。看来你不需要在这里聚合。