SQL按年分组

时间:2014-10-06 16:18:47

标签: sql

使用w3schools db,我必须创建这些查询。我被困在几个问题上,以为我会问......

Q2:显示前5名员工,不包括最高员工(显示员工排名2-5),这些员工的总销售额。在查询中显示员工的名字,姓氏和TotalSales按降序排序。仅对1996年完成的订单过滤数据。

没有年份过滤的代码是:

SELECT e.LastName, e.FirstName, SUM(od.Quantity*p.Price) AS OrderTotal
FROM [Employees] AS e 
JOIN [Orders] AS o ON o.EmployeeID=e.EmployeeID
JOIN [OrderDetails] AS od ON od.OrderID=o.OrderID
JOIN [Products] AS p ON od.ProductID=p.ProductID
GROUP BY e.EmployeeID
ORDER BY OrderTotal DESC
LIMIT 4
OFFSET 1

我不知道如何只在1996年通过订单返回它,当我尝试分组到1996年似乎没有帮助..

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用YEAR()函数。查看此有用的datetime函数列表。

尝试这个新查询:

SELECT e.LastName, e.FirstName, SUM(od.Quantity*p.Price) AS OrderTotal
FROM [Employees] AS e 
JOIN [Orders] AS o ON o.EmployeeID=e.EmployeeID
JOIN [OrderDetails] AS od ON od.OrderID=o.OrderID
JOIN [Products] AS p ON od.ProductID=p.ProductID
WHERE YEAR([OrderDate]) = 1996
GROUP BY e.EmployeeID
ORDER BY OrderTotal DESC
LIMIT 4
OFFSET 1

答案 1 :(得分:1)

由于用于w3schools的WebSQL数据库似乎不支持year(),我认为你可以使用它代替:

SELECT e.LastName, e.FirstName, SUM(od.Quantity*p.Price) AS OrderTotal
FROM [Employees] AS e 
JOIN [Orders] AS o ON o.EmployeeID=e.EmployeeID
JOIN [OrderDetails] AS od ON od.OrderID=o.OrderID
JOIN [Products] AS p ON od.ProductID=p.ProductID
WHERE OrderDate BETWEEN '1996-01-01' AND '1996-12-31'
GROUP BY e.EmployeeID
ORDER BY OrderTotal DESC
LIMIT 4
OFFSET 1

当我使用Chrome(但不是Firefox)进行测试时似乎有效

答案 2 :(得分:0)

CODE:

WHERE DATEPART(year, [OrderDate])=1996