Thursday, January 2, 2020

CROSS APPLY in T-SQL is different from just a CTE or subselect in that you basically spec out a table to be joined in a query wherein that table is defined by a second, nested query.

Stack Overflow had the following example:

USE Northwind
GO
SELECT o1.OrderID, o1.OrderDate, ca.OrderID AS NextOrder, ca.OrderDate AS
      NextOrderDate, CustomerID, DATEDIFF(DAY, o1.OrderDate, ca.OrderDate)
      DaysToNextOrder
FROM Orders AS o1
   CROSS APPLY
      (SELECT TOP 1 o.OrderDate, o.OrderID
      FROM Orders AS o
      WHERE o.customerID = o1.customerID AND o.OrderID > o1.OrderID
      ORDER BY OrderID) AS ca
ORDER BY CustomerID, o1.OrderID

 
 

I guess this behaves like an inner join and you use OUTER APPLY instead of using CROSS APPLY to have an outer join effect.

No comments:

Post a Comment