order by子句在视图中无效

时间:2018-04-13 06:51:10

标签: sql sql-server

以下脚本的输出是:

  

ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOP,OFFSET或FOR XML。

任何单挑?

SELECT *
FROM
(
       SELECT *,ROW_NUMBER() OVER (PARTITION BY [ID] ORDER BY [Date] DESC) [Order]  
       FROM
       (
              SELECT

                     A.[ID],
                     B.[UID],
                     C.[Date] 
              FROM Sample_1 A
              FULL JOIN Sample_2 B
              ON A.[ID] = B.[ID]
              FULL JOIN Sample_3 C
              ON A.[ID] = C.[ID]
              WHERE A.[SourceFile] BETWEEN 1 AND 100
              order by [ID]
       ) a
       WHERE [Date] < '2018/02/16' 
) b
WHERE [Order] = 1  
ORDER BY [ID],[Date]

3 个答案:

答案 0 :(得分:0)

  

请尝试此操作,因为ORDER BY子句在视图中无效,内联   函数,派生表,子查询和公用表表达式

SELECT *
FROM
(
       SELECT *,ROW_NUMBER() OVER (PARTITION BY [ID] ORDER BY [Date] DESC) [Order]  
       FROM
       (
              SELECT

                     A.[ID],
                     B.[UID],
                     C.[Date] 
              FROM Sample_1 A
              FULL JOIN Sample_2 B
              ON A.[ID] = B.[ID]
              FULL JOIN Sample_3 C
              ON A.[ID] = C.[ID]
              WHERE A.[SourceFile] BETWEEN 1 AND 100
              --order by [ID] (this is the cause of the error) 
       ) a
       WHERE [Date] < '2018/02/16' 
) b
WHERE [Order] = 1  
ORDER BY [ID],[Date]

答案 1 :(得分:0)

今天就我的情况而言,我同意@Sparky。

d_e62 <- db_read(con, 
"select top 100 percent
campus2,
avg(fg) as mfg,
avg(cpw) as mcpw,
avg(LOS) as mlos

from
danall

where
ARDRG70 like 'E62%'
and w22wiesfund = 'Y'

group by
campus2

order by campus2")

前100%让我包括订单,否则得到上面的错误。

答案 2 :(得分:-1)

似乎对我的回答有些困惑。我建议操作系统添加选择前100%* 以允许创建视图。我并不是建议他们通过

删除订单

参见下面的示例

create view dbo.TestView1
as
select * from ls.models order by model_number
-- 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.
go
create view dbo.TestView2
as
select top 100 percent * from ls.models order by model_number
go
select * from dbo.TestView2

要修复&#34;问题&#34;,请使用以下代码段

 SELECT TOP 100 PERCENT 
                     A.[ID],
                     B.[UID],
                     C.[Date] 
              FROM Sample_1 A
              FULL JOIN Sample_2 B
              ON A.[ID] = B.[ID]
              FULL JOIN Sample_3 C
              ON A.[ID] = C.[ID]
              WHERE A.[SourceFile] BETWEEN 1 AND 100
              order by [ID]