Northwind - 员工最近的客户ID

时间:2014-09-18 21:03:32

标签: sql sqlite northwind

在Northwind示例数据库中,我尝试获取每位员工最近订单的OrderID,我使用的是:

SELECT EmployeeID, MAX(OrderDate) AS OrderDate, COUNT(OrderDate) AS Count, 
    (SELECT OrderID 
     FROM Orders 
     WHERE OrderDate = (SELECT MAX(OrderDate) 
                        FROM Orders)
    ) AS OrderID
FROM Orders
GROUP BY EmployeeID

返回:

EmployeeID  OrderDate       Count   OrderID
1           1997-01-06      29      10443
2           1997-01-22      20      10443
3           1997-02-11      31      10443
4           1997-02-10      40      10443
5           1996-12-27      11      10443
6           1997-02-07      18      10443
7           1997-01-28      14      10443
8           1997-02-12      27      10443
9           1997-01-10      6       10443

但问题是它只是获取最新的OrderID并显示所有员工,而不是每个员工。我该怎么做才能解决这个问题?

由于

1 个答案:

答案 0 :(得分:0)

我对您的查询做了一些更改。希望它有所帮助。

SELECT EmployeeID, MAX(OrderDate) AS OrderDate, COUNT(OrderDate) AS Count, 
    (SELECT MAX(OrderID) 
     FROM Orders 
     WHERE EmployeeID = O.EmployeeID
     ) AS OrderID
FROM Orders O
GROUP BY EmployeeID