2015-10-20 136 views
0

我對SQL非常陌生,正在編寫一個腳本來提取2015年9月30日之前發生的事務。我收到了錯誤消息 - 關鍵字'WHERE'附近的語法錯誤。SQL中的語法錯誤where子句

我在做什麼錯?

SELECT 
    T1.Account, 
T2.AcctName, 
    SUM(T1.Debit - T1.Credit) AS 'Balance', 
    Sum(T1.SysDeb - T1.SysCred) AS 'USDBalance' 
FROM OJDT T0 
INNER JOIN JDT1 T1 ON T0.TransId = T1.TransId 
Left Join OACT T2 ON T2.AcctCode = T1.Account 
GROUP BY 
T1.Account, T2.AcctName WHERE T1.Refdate <= '09-30-2015' 

回答

5

WHERE而來的GROUP BY前:

Select  T1.Account, 
      T2.AcctName, 
      Sum(T1.Debit - T1.Credit) As 'Balance', 
      Sum(T1.SysDeb - T1.SysCred) As 'USDBalance' 
From  OJDT T0 
Inner Join JDT1 T1 ON T0.TransId = T1.TransId 
Left Join OACT T2 ON T2.AcctCode = T1.Account 
Where  T1.Refdate <= '09-30-2015' 
Group By T1.Account, T2.AcctName 
+0

謝謝!這工作完美。我感謝您花時間回覆 –

1

可以使用CROSS APPLY簡化一些的GROUP BY的複雜性。在下面,這段代碼執行並返回與上述答案相同的結果。

SELECT 
    balances.Account, 
    balances.AcctName, 
    balances.Balance AS 'Balance', 
    balances.USDBalance AS 'USDBalance' 
FROM OJDT T0 
CROSS APPLY (
    SELECT 
     SUM(T1.Debit - T1.Credit) AS Balance, 
     Sum(T1.SysDeb - T1.SysCred) AS USDBalance, 
     T1.Account AS Account, 
     T2.AcctName AS AcctName 
    FROM JDT1 T1 
    LEFT OUTER JOIN OACT T2 ON T2.AcctCode = T1.Account 
    WHERE T1.TransId = T0.TransId AND T1.Refdate <= '09-30-2015' 
) balances