ORDER BY 子句在视图、内联函数、派生 table、子查询和常见 table 表达式中无效,除非 TOP、OFFSET 或 FOR XML

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML

我有一个查询,我想通过 CreatationDateTime 表单 requestFolders 进行订购 但是我得到这个错误。

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

我的查询是:

with requests as    (
select IRF.Id as Id,
    P.Id as ProcessId,
    N'Investment' as [ServiceType],
    IRF.FolderNumber as FolderNumber,
    P.[Name] as [TypeTitle],
    S.CustomerDisplayInfo_CustomerTitle as [CurrentStatus],
    S.CustomerDisplayInfo_CustomerOrder as [CurrentStatusOrder],
    RH.OccuredDateTime as [CurrentStatusDate],
    IRF.CreationDateTime as [RequestDate],
    IRF.RequestedAmount as [Amount],
    (case when A.Id is not Null and s.sidetype='CustomerSide' then 1 else 0 end)  as [HasAction],
    rank() over ( partition by IRF.Id order by rh.OccuredDateTime desc) as rnk
from
    [Investment].[dbo].[InvestmentRequestFolders] as IRF inner join
    [Investment].[dbo].[RequestHistories] as RH on IRF.Id = RH.ObjectId inner join
    [Investment].[dbo].[Processes] as P on P.Id = RH.ProcessId inner join
    [Investment].[dbo].[Step] as S on S.Id = RH.ToStep left join
    [Investment].[dbo].[Actions] as A on A.StepId = RH.ToStep

where IRF.Applicant_ApplicantId = '89669CD7-9914-4B3D-AFEA-61E3021EEC30'

-- the error is here
order by IRF.CreationDateTime

) SELECT t.Id,
    max(t.ProcessId) as [ProcessId],
    t.[ServiceType] as [ServiceType],
    isnull(max(t.TypeTitle), '-') as [TypeTitle],
    isnull(max(t.FolderNumber), '-') as [RequestNumber],
    isnull(max(t.CurrentStatus), '-') as [CurrentStatus],
    isnull(max(t.CurrentStatusOrder), '-') as [CurrentStatusOrder],
    max(t.CurrentStatusDate)as [CurrentStatusDate],
    max(t.RequestDate) as [RequestDate],
    max(t.HasAction) as [HasAction],
    isnull(max(t.Amount), 0) as [Amount]
FROM requests as t

where t.rnk = 1

GROUP BY t.Id

错误出现在消息 1033、级别 15、状态 1、第 24 行

请帮帮我。

在几乎所有情况下,您都可以简单地删除 CTE 的 ORDER BY 子句。即使它在句法上是允许的(它在其他 RDBMS 中),它对您的查询结果的编写方式没有影响。

现在,如果出于某种原因,您绝对必须将其保留在那里,您可以添加一个 TOP 子句,例如一个没有任何影响,例如 TOP 100 PERCENT,即:

with requests as    (
  select top 100 percent
    IRF.Id as Id,
    ...

一个完整的简化示例:

-- Doesn't work
with t (a) as (
  select a
  from (values (1),(3),(2)) t (a)
  order by a
)
select a from t order by a

-- Works
with t (a) as (
  select top 100 percent a
  from (values (1),(3),(2)) t (a)
  order by a
)
select a from t order by a