问题描述
我有一个查询,我想通过 CreationDateTime 表单 requestFolders 订购 但是我收到了这个错误。
ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效,除非还指定了 TOP、OFFSET 或 FOR XML。
我的查询是:
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),(2)) t (a)
order by a
)
select a from t order by a