错误:order by子句在视图中无效

时间:2019-02-27 16:02:30

标签: sql sql-server

我在SQL Server 14中遇到以下错误,其中我试图基于4个表构建视图

  

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

如何解决以下问题,以免出现此错误?

SELECT        dbo.PS_Proj.[Project ID],
            case 
            when PS_Proj.[City Name] is not null then  concat(PS_Proj.[City Name], ' ', PS_Proj.[State])
            when PS_Billing.[Location] is not null then max(PS_Billing.[Location])
            when PS_Time.[Labor Location ID] is not null then max(PS_Location.[Labor Location Name])
            else null
            end AS [Location]
FROM        dbo.PS_Location RIGHT OUTER JOIN
                     dbo.PS_Time ON dbo.PS_Location.[Labor Location ID] = dbo.PS_Time.[Labor Location ID] RIGHT OUTER JOIN
                     dbo.PS_Proj ON dbo.PS_Time.[Project ID] = dbo.PS_Proj.[Project ID] LEFT OUTER JOIN
                     dbo.PS_Billing ON dbo.PS_Proj.[Project ID] = dbo.PS_Billing.[Project ID]
ORDER BY    PS_Billing.[T/S Date], PS_Time.[Date]

我想显示最新的PS_Billing位置,如果要显示最新的PS_Time位置,则为null。

2 个答案:

答案 0 :(得分:2)

创建不带“排序依据”的视图。删除ORDER BY PS_Billing。[T / S日期],PS_Time。[日期],然后将它们添加到您的SELECT中。

SELECT     
PS_Billing.[T/S Date] AS TsDate, 
PS_Time.[Date] AS Date,
 dbo.PS_Proj.[Project ID],
            case 
            when PS_Proj.[City Name] is not null then  concat(PS_Proj.[City Name], ' ', PS_Proj.[State])
            when PS_Billing.[Location] is not null then max(PS_Billing.[Location])
            when PS_Time.[Labor Location ID] is not null then max(PS_Location.[Labor Location Name])
            else null
            end AS [Location]
FROM        dbo.PS_Location RIGHT OUTER JOIN
                     dbo.PS_Time ON dbo.PS_Location.[Labor Location ID] = dbo.PS_Time.[Labor Location ID] RIGHT OUTER JOIN
                     dbo.PS_Proj ON dbo.PS_Time.[Project ID] = dbo.PS_Proj.[Project ID] LEFT OUTER JOIN
                     dbo.PS_Billing ON dbo.PS_Proj.[Project ID] = dbo.PS_Billing.[Project ID] 

并按行顺序从视图中选择

Select FROM YOUR_VIEW_NAME as V
Order By V.TsDate, V.Date

答案 1 :(得分:0)

您的案例表达式中有一些汇总数据,而没有分组依据。我在这里猜测。另外,您应该养成使用别名的习惯,这会使事情变得简单得多。我还建议不要在列名称中添加空格,因为这会迫使您不断将列包装在方括号中。

这样的事情应该让你靠近。

SELECT p.[Project ID]
    , MAX(case 
        when p.[City Name] is not null then concat(p.[City Name], ' ', p.[State])
        when b.[Location] is not null then b.[Location]
        when t.[Labor Location ID] is not null then l.[Labor Location Name]
        else null
    end) AS [Location]
FROM dbo.PS_Location l
RIGHT OUTER JOIN dbo.PS_Time t ON l.[Labor Location ID] = t.[Labor Location ID] 
RIGHT OUTER JOIN dbo.PS_Proj  p ON t.[Project ID] = p.[Project ID]
LEFT OUTER JOIN dbo.PS_Billing b ON p.[Project ID] = b.[Project ID]
GROUP BY p.[Project ID]