Posted on: 3/13/2015 3:11:02 PM | Views : 897

Hi all,
From Page 88 of the Book "SQL Programming & Database Design Using Microsoft SQL Server 2012" written by Kalman Toth, I copied the following code of Using CTE in a query:
-- CTETest2.sql /// saved in C:\My Documents\SQL Server Management Studio\ ----Page 88 of Book by Toth === Using CTE in a query ----- 13 March 2015 --Using CTE in a query ;WITH CTE (SalesPersonID, NumberOfOrders, MostRecentOrderDate) AS (SELECT SalesPersonID, COUNT(*), CONVERT(date, MAX(OrderDate)) FROM Sales.SalesOrderHeader GROUP BY SalesPersonID ) --Start of outer (main) query SELECT E.EmployeeID, OE.NumberOfOrders AS EmpOrders, OE.MostRecentOrderDate AS EmpLastOrder, E.ManagerID, OM.NumberOfOrders AS MgrOrders, OM.MostRecentOrderDate AS MgrLastOrder FROM HumanResources.Employee AS E INNER JOIN CTE AS OE ...

Go to the complete details ...