我需要在一小时内插入同一位客户的前1条记录。如果一小时后插入记录,则不需要该记录。请参见下表。这只是1000条记录的样本。我正在使用SQL Server 2005。
替代文字http://img651.imageshack.us/img651/3990/customershavingmultiple.png
想法如下
SQL语句
UPDATE Orders SET ParentOrderID = p.ParentOrderID FROM Orders o INNER JOIN ( SELECT ParentOrderID = MIN(o1.OrderID), OrderID = o2.OrderID FROM Orders o1 LEFT OUTER JOIN Orders o2 ON o2.CustomerID = o1.CustomerID AND o2.OrderDate > o1.OrderDate AND DATEADD(hh, -1, o2.OrderDate) < o1.OrderDate GROUP BY o2.OrderID ) p ON p.OrderID = o.OrderID