使用 Union All 和 Order By In View?

Use Union All & Order By In View?

我需要按视图中两个表中包含的日期列进行排序。以下是我用于我的视图的语法,但是如果我尝试在视图中使用 order by 语句,我会收到此错误:

Msg 1033, Level 15, State 1, Procedure TransFund_Lead_Upload_File, Line 63

The ORDER BY clause is invalid in views, inline functions, derived tables, and subqueries, unless TOP is also specified.

这是我的查询语法..需要更改什么以便我可以按 [Follow Up] Desc 订购?

SELECT * FROM
(
Select
'abcd' As [P]
,ISNULL(Building_Name,'') As [Building_Name]
,ISNULL(ID,'') As [Record ID]
,ISNULL(city,'') + ', ' + ISNULL([state],'') As [Zone]
,ISNULL(CONVERT(VARCHAR(10), [Sale Date], 101),'') As [Actual Sale Date]
,'' As [Begin Effort]
,ISNULL(CAST(sold_items AS VARCHAR(500)),'') As [Items List]
,ISNULL(CAST(wascoreItemSold AS Varchar(500)),'') As [Info]
,ISNULL(CONVERT(VARCHAR(10), followupdate, 101),'') As [Follow Up]
FROM dbo.esrt b
UNION ALL
Select
'eeee' As [P]
,ISNULL(Building_Name,'') As [Building_Name]
,ISNULL(ID,'') As [Record ID]
,ISNULL(city,'') + ', ' + ISNULL([state],'') As [Zone]
,ISNULL(CONVERT(VARCHAR(10), Sale Date, 101),'') As [Actual Sale Date]
,'' As [Begin Effort]
,ISNULL(CAST(sold_items AS Varchar(500)),'') As [Items List]
,ISNULL(CAST(wascoreItemSold AS Varchar(500)),'') As [Info]
,ISNULL(CONVERT(VARCHAR(10), followupdate, 101),'') As [Follow Up]
FROM dbo.foxtrot a
) a
ORDER BY a.[Follow Up] DESC

由于视图被视为子查询,因此排序会强制执行额外的工作。 SQL 服务器将自动对表或视图中的数据进行排序以优化查找结果,这就是结果可以随机顺序返回的原因。使用视图对查询进行的任何筛选和排序都会否定视图的排序子句。此外,根据您的视图正在执行的操作,SQL 服务器可能会选择将视图的内容提取到主查询中,以便在单个查询计划中进一步优化它。

请记住,SQL服务器本身并不关心它接收或传送结果的顺序。 TOP 语句告诉 SQL 服务器有明确的理由需要对记录进行排序,因为它会影响返回的结果。

当您 select 您的查询结果时,您必须进行排序。

SELECT *
FROM MyView
ORDER BY [Follow Up] DESC;