日期:2014-05-17  浏览次数:20603 次

老看不明白这个查询
use Northwind
go
SELECT OrderID, CustomerID, EmployeeID, OrderDate, RequiredDate 
FROM dbo.Orders AS O1
WHERE OrderDate =
  (SELECT MAX(OrderDate)
   FROM dbo.Orders AS O2
   WHERE O2.EmployeeID = O1.EmployeeID
   );

上面是可以执行的。我用子查询独立执行,执行不了。我改了一下,如下,还是执行不了。请教为什么?这是不是一个内外交叉的母子查询,请问流程是怎么走法的?OrderDate应该只能取唯一值,为啥出来的结果有好多条记录?
SELECT MAX(OrderDate)
   FROM dbo.Orders AS O2 join dbo.Orders AS O1
   WHERE O2.EmployeeID = O1.EmployeeID

------解决方案--------------------
这个叫做相关子查询,就是外部对象参与内部子查询的筛选
流程大概是,检索出的外部数据1条,然后在子查询中筛选该条件中的最大date
再与外部date进行筛选

SELECT EmployeeID,MAX(OrderDate)
FROM dbo.Orders
group by EmployeeID
------解决方案--------------------
查询每个employee最后一次下单的OrderID, CustomerID, EmployeeID, OrderDate, RequiredDate ,原来查询中的Max(OrderDate)是针对每一个employee 有一个Max,每个有过记录的雇员,就会有一笔,所以最终结果不是只有一笔.
------解决方案--------------------
1.首先说你的子查询吧,您Join 后面没有 on
2.为什么会有多条结果?
SELECT MAX(OrderDate)    
FROM dbo.Orders AS O2    
WHERE O2.EmployeeID = O1.EmployeeID 

获得某个EmployeeID的最大OrderDate,你应该有多个EmployeeID吧,所以OrderDate也有多个喽。

3.流程  Loop 
       Begin
         从01中取出一个EmployeeIDea
         根据这个EmployeeID在02找出最大OrderDate
        END