我在下方查询了=>
SELECT FirstName,
LastName,
COUNT(*) AantalBestellingen,
YEAR(Orders.OrderDate) as Jaar
from Employees
RIGHT JOIN Orders ON (Employees.EmployeeID=Orders.EmployeeID)
WHERE Employees.ReportsTo IS NOT NULL
GROUP BY Employees.FirstName, Employees.LastName, YEAR (Orders.OrderDate)
ORDER BY YEAR (Orders.OrderDate)
我需要选择员工的名字,姓氏以及他们去年处理的总订单。
在查询中按年份添加组后,它不再显示唯一的员工,但会显示年份。我只需要获得独特的员工以及他们处理订单的最后一个订单年度。
我有什么建议我做错了吗?
答案 0 :(得分:1)
一种方法是使用内部选择:
SELECT
FirstName,
LastName,
COUNT(*) as AantalBestellingen,
(select YEAR(max(Orders.OrderDate)) from Orders O
where Employees.EmployeeID=O.EmployeeID) as Jaar
from
Employees
RIGHT JOIN Orders
ON (Employees.EmployeeID=Orders.EmployeeID)
WHERE
Employees.ReportsTo IS NOT NULL
GROUP BY
Employees.FirstName,
Employees.LastName
ORDER BY Jaar
答案 1 :(得分:0)
您可以将Last Year条件放在WHERE子句中,如下所示
SELECT FirstName,
LastName,
COUNT(*) AantalBestellingen,
from Employees
RIGHT JOIN Orders ON (Employees.EmployeeID=Orders.EmployeeID)
WHERE Employees.ReportsTo IS NOT NULL AND YEAR(Orders.OrderDate) = 2014
GROUP BY Employees.FirstName, Employees.LastName
答案 2 :(得分:0)
你能试试这个......这将给所有员工,他去年唯一的订单和去年。
;with cteMaxYear as
(select max(YEAR(Orders.OrderDate)) MaxOrderYear, EmployeeID
from Orders
group by EmployeeID)
SELECT FirstName,
LastName,
COUNT(*) AantalBestellingen,
m.MaxOrderYear as Jaar
from Employees e
left outer join cteMaxYear m
inner join Orders o ON m.EmployeeID=o.EmployeeID and m.MaxOrderYear=o.YEAR(Orders.OrderDate)
on e.EmployeeID = m.EmployeeID
WHERE e.ReportsTo IS NOT NULL
GROUP BY e.FirstName, e.LastName, m.MaxOrderYear
ORDER BY m.MaxOrderYear