SQL查询中的Orderby子句错误

时间:2018-04-30 07:17:53

标签: sql sql-server-2012

我在执行以下查询时遇到错误:

INSERT Into dbo.[DRC_76_A-05 Deposits SBP Coding] 
SELECT '20180228' as BusinessDate,z.* 
FROM ( SELECT IND.L_SBP_CODE, TDEPO.Type_of_Deposit, 
              ISNULL(SUM(AC.WORKING_BALANCE),0) AS AMOUNT 
       FROM InsightSource.BS.ACCOUNT AC 
       LEFT JOIN InsightSource.BS.CUSTOMER CUS ON AC.CUSTOMER = CUS.[@ID] 
       INNER JOIN KMBL.DBO.TYPE_OF_DEPOSITS TDEPO ON AC.CATEGORY = TDEPO.Cat_ID 
       LEFT JOIN InsightSource.BS.INDUSTRY_LocalRef IND ON CUS.INDUSTRY = IND.[@Id] 
       GROUP BY IND.L_SBP_CODE, TDEPO.Type_of_Deposit 
       ORDER BY TDEPO.Type_of_Deposit ASC ) Z

错误:

  

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

2 个答案:

答案 0 :(得分:1)

您应该在子查询之外移动ORDER BY

  INSERT Into dbo.[DRC_76_A-05 Deposits SBP Coding] 
  Select '20180228' as BusinessDate,z.* 
  From ( 
      SELECT IND.L_SBP_CODE
            , TDEPO.Type_of_Deposit
            , ISNULL(SUM(AC.WORKING_BALANCE),0) AS AMOUNT 
      FROM InsightSource.BS.ACCOUNT AC 
      LEFT JOIN InsightSource.BS.CUSTOMER CUS ON AC.CUSTOMER = CUS.[@ID] 
      INNER JOIN KMBL.DBO.TYPE_OF_DEPOSITS TDEPO ON AC.CATEGORY = TDEPO.Cat_ID 
      LEFT JOIN InsightSource.BS.INDUSTRY_LocalRef IND ON CUS.INDUSTRY = IND.[@Id] 
      GROUP BY IND.L_SBP_CODE, TDEPO.Type_of_Deposit 
 ) Z
  ORDER BY Z.Type_of_Deposit ASC

答案 1 :(得分:0)

错误消息是不言自明的:

  

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

您正在子查询中执行ORDER BY。它在所有情况下都是无用的,所以你可以简单地摆脱它。

在收集和过滤所有数据时,在主查询中执行ORDER BY