【发布时间】:2026-02-04 21:40:01
【问题描述】:
我有一个查询,我想通过 CreatationDateTime 表单 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
错误出现在 Msg 1033, Level 15, State 1, Line 24
请帮帮我。
【问题讨论】:
-
错误是字面上告诉你问题;有什么你不明白的,我们可以尝试详细说明。
-
您可以尝试在主查询上放置 ORDER BY 以对查询的最终结果的行进行排序。如果这不是您想要或需要的,您应该更详细地解释。
-
CTE 在逻辑上是一个表——实际上只是派生表的语法糖。在最终的 SELECT 语句中对结果集进行排序,而不是在 CTE 中。相关 - 您(或更可能是其他人)会后悔使用 3 个部分名称。让连接确定要使用的数据库。在将您的代码用于其他数据库时,不要添加其他人必须解决的问题。
-
ORDER BY 子句 这是带有
order by的SQL 语句的一部分无效 表示无效在视图中 用create view声明的东西,内联函数 带有单个return的表函数,派生表 在select周围使用()声明, 子查询类似,除了它们在其他表达式中,和公用表表达式由with声明除非TOP、OFFSET或FOR XML也指定 其中之一必须是同一select的一部分。如果你能告诉我们你想用order by做什么,也许我们可以提供帮助。
标签: sql sql-server sql-server-2017