我在 SQL Server 2008/2012 上。我有一个计数表#MonthTally
;WITH
Pass0 AS (SELECT 1 AS C UNION all SELECT 1), --2 rows
Pass1 AS (SELECT 1 AS C FROM Pass0 AS A, Pass0 AS B),--4 rows
Pass2 AS (SELECT 1 AS C FROM Pass1 AS A, Pass1 AS B),--16 rows
Pass3 AS (SELECT 1 AS C FROM Pass2 AS A, Pass2 AS B),--256 rows
Tally AS (SELECT ROW_NUMBER() OVER(ORDER BY C) AS N FROM Pass3)
SELECT TOP 256 ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS N
INTO #MonthTally
FROM Tally
ORDER BY N
我正在使用这样的计数表
-- Insert 5 future years
SELECT TOP(5) V.CompanyId, V.StartDate, V.EndDate
FROM #MonthTally T
CROSS APPLY
(
SELECT
F.CompanyId,
DATEADD(YY, T.N,MAX(F.StartDate)) AS StartDate,
DATEADD(YY, T.N,MAX(F.EndDate)) AS EndDate
FROM FiscalPeriods F
GROUP BY CompanyId
) V
我已经读过,每当您使用 TOP 时,您应该始终使用 ORDER BY 来确保 TOP 返回什么。所以我不能指望SELECT TOP(5) * FROM #MonthTally
总是返回 1 到 5,除非我使用 ORDER BY,不管数据是如何插入到#MonthTally
. 但是如何在我的 CROSS APPLY 上获得 ORDER BY。
它不会更糟,然后我可以在 CROSS APPLY 之外进行聚合。无论如何,它对每条线的 GROUP BY 可能表现不佳。但无论如何我都想知道。