
For info, I checked whether LINQ-to-SQL does it correctly, and it
seems to; using NWind:
ctx.Log = Console.Out;
var qry = (from order in ctx.Orders
orderby order.Freight, order.OrderID
select new {
Order = order,
Lines = order.Order_Details.Count() })
.Take(20)
.OrderBy(x => x.Order.OrderID)
.ToList();
gives TSQL as below; complex looking, but does what we want in the
right order...
Marc
SELECT [t3].[OrderID], [t3].[CustomerID], [t3].[EmployeeID], [t3].
[OrderDate], [
t3].[RequiredDate], [t3].[ShippedDate], [t3].[ShipVia], [t3].
[Freight], [t3].[Sh
ipName], [t3].[ShipAddress], [t3].[ShipCity], [t3].[ShipRegion], [t3].
[ShipPosta
lCode], [t3].[ShipCountry], [t3].[value] AS [Lines]
FROM (
SELECT TOP (20) [t2].[OrderID], [t2].[CustomerID], [t2].
[EmployeeID], [t2].[
OrderDate], [t2].[RequiredDate], [t2].[ShippedDate], [t2].[ShipVia],
[t2].[Freig
ht], [t2].[ShipName], [t2].[ShipAddress], [t2].[ShipCity], [t2].
[ShipRegion], [t
2].[ShipPostalCode], [t2].[ShipCountry], [t2].[value]
FROM (
SELECT [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID],
[t0].[Order
Date], [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].
[Freight],
[t0].[ShipName], [t0].[ShipAddress], [t0].[ShipCity], [t0].
[ShipRegion], [t0].[S
hipPostalCode], [t0].[ShipCountry], (
SELECT COUNT(*)
FROM [dbo].[Order Details] AS [t1]
WHERE [t1].[OrderID] = [t0].[OrderID]
) AS [value]
FROM [dbo].[Orders] AS [t0]
) AS [t2]
ORDER BY [t2].[Freight], [t2].[OrderID]
) AS [t3]
ORDER BY [t3].[OrderID], [t3].[Freight]