无法将别名用于GROUP BY子句

时间:2017-10-17 00:39:54

标签: sql tsql

我已加入大型查询

LEFT JOIN --RIVA MICRO
    (SELECT 
         TT.DATAAREAID, TT.VOUCHER,MA.MAINACCOUNTID AS AD,
         SUM(TT.TAXBASEAMOUNT) AS TAXBASEAMOUNT,
         SUM(TT.TAXAMOUNT) AS TAXAMOUNT 
     FROM 
         TAXTRANS TT
     INNER MERGE JOIN 
         TAXTRANSDETAIL_BE MA ON TT.RECID = MA.RECID
     WHERE 
         TT.TRANSDATE <= @FECHA AND ("+@Codigo_RIVA+")
     GROUP BY 
         TT.DATAAREAID, TT.VOUCHER, MA.MAINACCOUNTID) AS RIVA2 ON Asiento.Asiento = RIVA2.VOUCHER 
                                                               AND Asiento.Cuenta = RIVA2.AD
                                                               AND Asiento.Empresa = RIVA2.DATAAREAID

它工作正常,但现在我实现了一个临时表,所以我的查询就像:

LEFT JOIN 
    (SELECT 
         DATAAREAID, VOUCHER, MAINACCOUNTID,
         SUM(TAXBASEAMOUNT) AS TAXBASEAMOUNT, SUM(TAXAMOUNT)  
     FROM 
         ##TTM TT 
     WHERE 
        (TT.TAXCODE LIKE 'RIVA11DPT' OR  TT.TAXCODE LIKE 'RIVA16DPT' 
         OR  TT.TAXCODE LIKE 'RIVA16T')
     GROUP BY  
         TT.TAXAMOUNT, TT.TAXBASEAMOUNT, TT.TAXCODE, TT.DATAAREAID, 
         TT.VOUCHER, TT.MAINACCOUNTID) AS RIVA2 ON Asiento.Asiento = RIVA2.VOUCHER 
                                                AND Asiento.Cuenta = RIVA2.MAINACCOUNTID
                                                AND Asiento.Empresa = RIVA2.DATAAREAID

但现在问题是GROUP BY CLAUSE,我进入了别名AS RIVA2

  

关键字“AS”附近的语法不正确。

有人知道它为什么会发生吗?此致

1 个答案:

答案 0 :(得分:2)

我想你打算:

LEFT JOIN 
(SELECT TT.DATAAREAID, TT.VOUCHER, TT.MAINACCOUNTID,
        SUM(TT.TAXBASEAMOUNT) AS TAXBASEAMOUNT, SUM(TT.TAXAMOUNT)  
 FROM ##TTM TT 
 WHERE TT.TAXCODE IN ('RIVA11DPT', 'RIVA16DPT', 'RIVA16T')
 GROUP BY TT.DATAAREAID, TT.VOUCHER, TT.MAINACCOUNTID
) RIVA2   
ON Asiento.Asiento = RIVA2.VOUCHER AND
   Asiento.Cuenta = RIVA2.MAINACCOUNTID AND
   Asiento.Empresa = RIVA2.DATAAREAID

注意:

  • 您只需按GROUP BY中的 unaggregated 列进行汇总。
  • 众所周知,您无法在与SELECT关联的大多数其他子句中使用SELECT中定义的列别名。
  • INOR子句的集合简单得多。
  • 您应该给SUM(TT.TAXAMOUNT)一个名字。