order by子句的SQL错误

时间:2016-05-02 17:53:12

标签: sql sql-server sql-order-by ssms-2014

我收到错误

  

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

代码如下,

SELECT      MIDDLE.MODEL AS Model,  
                    MIDDLE.MANUFACTURER AS Manufacturer,
                    {fn CONCAT(CAST(AVG(ABS(MIDDLE.AVG_YEAR)/365) as Decimal(10, 2)), ' Years')} AS AverageAge, 
                    {fn CONCAT('$',CAST(SUM(MIDDLE.ACQCOST) as Decimal(15,2)))} AS TotalAcquistionCost, 
                    {fn CONCAT('$',CAST(AVG(MIDDLE.ACQCOST) as Decimal(15,2)))} AS AverageAcquistionCost,  
                    {fn CONCAT('$',CAST(SUM(MIDDLE.SUMofSPENT) as Decimal(15,2)))} AS TotalRepairCost, 
                    {fn CONCAT('$',CAST(AVG(MIDDLE.SUMofSPENT) as Decimal(15,2)))} AS AverageRepairCost 
        FROM 

            (SELECT   
                    PRE.Model AS MODEL, 
                    PRE.Manufacturer AS MANUFACTURER, 
                    PRE.Avg_Year AS AVG_YEAR, 
                    PRE.AcqCost AS ACQCOST, 
                    SUM(PRE.Spent) AS SUMofSPENT FROM 
             (SELECT  

                    E.sn AS SerialNumber, 
                    E.mdl AS Model, 
                    DATEDIFF(year, E.acq, GETDATE()) AS Avg_Year, 
                    E.cost AS AcqCost,  
                    E.mfr AS Manufacturer, 
                    FR.spent AS Spent 
                    FROM rme_failrepair AS FR 


            INNER JOIN rme_endo AS E 
                    ON FR.acq_id = E.acq_id 
                    AND FR.en_sn = E.en_sn
            WHERE E.mdl = @mdl

                     ORDER BY SerialNumber, Spent )AS PRE 
                     GROUP BY PRE.SerialNumber) AS MIDDLE

2 个答案:

答案 0 :(得分:0)

如评论中所述,这应该是查询。 另请注意,您的GROUP BY子句也是错误的。您在SELECT中包含了许多列,这些列未出现在GROUP BY

 SELECT      
        MIDDLE.MODEL AS Model,  
        MIDDLE.MANUFACTURER AS Manufacturer,
        {fn CONCAT(CAST(AVG(ABS(MIDDLE.AVG_YEAR)/365) as Decimal(10, 2)), ' Years')} AS AverageAge, 
        {fn CONCAT('$',CAST(SUM(MIDDLE.ACQCOST) as Decimal(15,2)))} AS TotalAcquistionCost, 
        {fn CONCAT('$',CAST(AVG(MIDDLE.ACQCOST) as Decimal(15,2)))} AS AverageAcquistionCost,  
        {fn CONCAT('$',CAST(SUM(MIDDLE.SUMofSPENT) as Decimal(15,2)))} AS TotalRepairCost, 
        {fn CONCAT('$',CAST(AVG(MIDDLE.SUMofSPENT) as Decimal(15,2)))} AS AverageRepairCost 
FROM 
(
    SELECT  
        E.sn AS SerialNumber
        E.mdl AS Model, 
        DATEDIFF(year, E.acq, GETDATE()) AS Avg_Year, 
        E.cost AS AcqCost,  
        E.mfr AS Manufacturer, 
        SUM(FR.Spent) AS SUMofSPENT
    FROM rme_failrepair AS FR INNER JOIN rme_endo AS E 
        ON FR.acq_id = E.acq_id AND FR.en_sn = E.en_sn
    WHERE E.mdl = @mdl
    GROUP BY 
        E.sn, E.mdl, DATEDIFF(year, E.acq, GETDATE()), E.cost, E.mfr
) AS MIDDLE

答案 1 :(得分:0)

如果您需要ORDER BY查看或derived table,则需要指定PERCENT

(SELECT  TOP 100 PERCENT 

                E.sn AS SerialNumber, 
                E.mdl AS Model, .....