如何在子查询中添加ORDER BY或SORTING?

时间:2015-09-23 07:47:49

标签: java sql-server-2008

这是一个查询,其中甚至包含分页,我需要按照我指定的某个列进行排序。

DECLARE @RowsPerPage INT = 100, @PageNumber INT =1 
SELECT DISTINCT * FROM 
(SELECT DISTINCT a.*,b.WorkflowId bWorkflowId,b.TRF_CompanyCoverage,
b.TRF_OrgID,b.TRF_Fundb_RepoNumber,b.TRF_WSC_PPI,b.TRF_BucketID,b.TRF_GAAPCode,b
.TRF_MarketCapUSD,b.TRF_OrgName,b.TRF_AutomationFlag,b.TRF_SmartPriority,b.TRF_I
ndustryName,b.TRF_ExchangeCountryCode,b.TRF_ExchangeCountryName,b.TRF_UserGroup,
Tasks.TaskId,Tasks.WorkflowId cworkFlowId,Tasks.TRFTaskId,Tasks.TaskName,
ROW_NUMBER() OVER (ORDER BY Tasks.WorkflowID) AS RowNum 
FROM  CCC_Filling_Metadata a,Fundamentals_Metadata b,Tasks 
WHERE a.WorkflowID=b.WorkflowID AND b.WorkflowID=Tasks.WorkflowID AND
Tasks.CreateDateTime >= '2015-01-01' 
AND  Tasks.CreateDateTime <= '2015-12-01' AND Tasks.Owner =  '0326271' AND 
Tasks.TaskStatus = 'open') AS SOD
WHERE SOD.RowNum BETWEEN ((@PageNumber-1)*@RowsPerPage)+1
AND @RowsPerPage*(@PageNumber) 
order by Tasks.TargetDate, Tasks.SmartPriority, Fundamentals_Metadata.TRF_MarketCapUSD desc

使用此查询我会得到这样的异常....

Msg 4104, Level 16, State 1, Line 17
The multi-part identifier "Tasks.TargetDate" could not be bound.
Msg 4104, Level 16, State 1, Line 17
The multi-part identifier "Tasks.SmartPriority" could not be bound.
Msg 4104, Level 16, State 1, Line 17
The multi-part identifier "Fundamentals_Metadata.TRF_MarketCapUSD" could not be bound.
Msg 145, Level 15, State 1, Line 2
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

请帮助我如何在此查询中使用“排序依据”...

1 个答案:

答案 0 :(得分:0)

您的外部查询是:

SELECT DISTINCT *
  FROM (...) AS SOD
 WHERE SOD.RowNum BETWEEN ((@PageNumber-1)*@RowsPerPage)+1 AND @RowsPerPage*(@PageNumber)
 ORDER BY Tasks.TargetDate, Tasks.SmartPriority, Fundamentals_Metadata.TRF_MarketCapUSD desc

因此,TasksFundamentals_Metadata是未知的限定符。删除它们,因为你只有一个&#34;视图&#34;名为SOD,因此不需要资格。

当然,您需要将Tasks.TargetDateTasks.SmartPriority添加到内部查询中,以便进行排序。