了解每位员工最畅销的产品

时间:2018-06-10 16:50:56

标签: sql aggregate-functions

我试图找出每位员工最畅销的产品(最喜欢的产品是什么)。

我有三个表,Sales(包含Quantity,Price和Product列),Products&员工,我知道这可以通过使用聚合来完成,但无法弄清楚逻辑。这就是我到目前为止所做的:

SELECT
    E.EmployeeID,
    FirstName,
    ProductID,
    SUM(Quantity) AS S,
    MAX(Quantity) AS M
FROM    
    tbl_Employees AS E
INNER JOIN
    tbl_Sales AS S ON E.EmployeeID = S.EmployeeID
GROUP BY
    ProductID, E.EmployeeID, FirstName

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您通常使用ANSI标准窗口函数执行此操作:

select s.*
from (select s.EmployeeID, s.ProductId, sum(s.quantity) as quantity,
             row_number() over (partition by s.EmployeeID order by sum(s.quantity) desc) as seqnum
      from tbl_sales s
      group by s.EmployeeID, s.ProductId
     ) s
where seqnum = 1;