0
對於家庭作業,我試圖在2012年1月使用AdventureWorks2014查找每位銷售人員的暢銷產品。使用SQL Server,我如何才能在AdventureWorks2014中找到每個銷售人員的暢銷產品?
這是我到目前爲止有:
SELECT
Person.Person.LastName, Person.Person.FirstName,
Person.Person.MiddleName,
Employee_1.JobTitle,
Sales.SalesPerson.SalesQuota, Sales.SalesOrderHeader.OrderDate,
Production.Product.Name,
SUM(distinct OrderQty) AS Expr2
FROM
Sales.SalesOrderDetail
INNER JOIN
Production.Product ON Sales.SalesOrderDetail.ProductID = Production.Product.ProductID
INNER JOIN
Sales.SalesOrderHeader ON Sales.SalesOrderDetail.SalesOrderID = Sales.SalesOrderHeader.SalesOrderID
AND Sales.SalesOrderDetail.SalesOrderID = Sales.SalesOrderHeader.SalesOrderID
AND Sales.SalesOrderDetail.SalesOrderID = Sales.SalesOrderHeader.SalesOrderID
INNER JOIN
Sales.SalesPerson ON Sales.SalesOrderHeader.SalesPersonID = Sales.SalesPerson.BusinessEntityID
AND Sales.SalesOrderHeader.SalesPersonID = Sales.SalesPerson.BusinessEntityID
AND Sales.SalesOrderHeader.SalesPersonID = Sales.SalesPerson.BusinessEntityID
AND Sales.SalesOrderHeader.SalesPersonID = Sales.SalesPerson.BusinessEntityID
INNER JOIN
HumanResources.Employee AS Employee_1
INNER JOIN
Person.Person ON Employee_1.BusinessEntityID = Person.Person.BusinessEntityID
ON Sales.SalesPerson.BusinessEntityID = Employee_1.BusinessEntityID
AND Sales.SalesPerson.BusinessEntityID = Employee_1.BusinessEntityID
WHERE
(Sales.SalesOrderHeader.OrderDate BETWEEN '2012-01-01' AND '2012-01-31')
GROUP BY
Person.Person.LastName, Person.Person.FirstName, Person.Person.MiddleName,
Employee_1.JobTitle,
Sales.SalesPerson.SalesQuota, Sales.SalesOrderHeader.OrderDate,
Production.Product.Name
ORDER BY
Person.Person.LastName, Production.Product.Name
我無法弄清楚如何添加orderqty所有爲每個單獨的產品。在前兩排結果中,我有同一人銷售的同一產品。我想將這些添加到一起,然後找到每個銷售人員擁有的前5名產品?
任何人都可以幫忙嗎?
您需要使用RANK()和PARTITION BY。這裏有很多例子,比如www.mikesknowledgebase.com/pages/SQLServer/Rank.htm –
@MikeGledhill [sql server'rank()'''row_number()'](http://stackoverflow.com/問題/ 7747327/sql-rank-versus-row-number) - 我想你的意思是'row_number()' – SqlZim