2015-10-13 100 views
1

我寫了甲骨文這個查詢,並希望編譯以及SQL Server上:別名在SQL Server

SELECT DISTINCT 
    HOLDER_CODE, CALCULATED_AMOUNT 
FROM 
    (SELECT 
     DA.HOLDER_CODE, 
     ROUND(FAB.AMOUNT * FCE.EXCHANGE_RATE,0) AS CALCULATED_AMOUNT, 
     FAB.BALANCE_DATE_ID as FAB_DATE, 
     MAX(FAB.BALANCE_DATE_ID) OVER (PARTITION BY DA.HOLDER_CODE) as MAX_DATE_BALANCE 
    FROM 
     DIM_ACCOUNT DA 
    JOIN 
     FACT_AS_BALANCE FAB ON FAB.ACCOUNT_ID = DA.ID 
    JOIN 
     DIM_AS_CHARACTERISTICS DAC ON DAC.ID = FAB.BALANCE_TYPE_ID 
    LEFT JOIN 
     FACT_CURRENCY_EXCHANGE FCE ON FCE.FROM_CURRENCY_ID = FAB.CURRENCY_ID 
    WHERE 
     DAC.BALANCE_CLOSING_FLAG = 'Y' 
     AND TO_CURRENCY_ID = (SELECT DC.ID 
           FROM DIM_CURRENCY DC 
           WHERE DC.IS_DEFAULT_CURRENCY = 'Y') 
     AND FAB.AMOUNT > 0) 
WHERE 
    FAB_DATE = MAX_DATE_BALANCE 
ORDER BY 
    CALCULATED_AMOUNT DESC; 

但是當我運行它,我得到以下異常:

Error: Incorrect syntax near the keyword 'WHERE'. SQLState: S0001 ErrorCode: 156

所以我想,這是最後的where子句,這表明了這一點。什麼是錯的,它應該是什麼?

+0

只要給一個別名,你的大子查詢中選擇不同於賦予一個名字...( ...)爲K,其中K.FAB_DATE ... – narendra

回答

11

你只需要別名子查詢

SELECT DISTINCT HOLDER_CODE, CALCULATED_AMOUNT 
FROM (
    SELECT DA.HOLDER_CODE, 
     //// snip subquery 
    AND FAB.AMOUNT > 0 
) alias_name_here //<--- here 
WHERE FAB_DATE = MAX_DATE_BALANCE 
ORDER BY CALCULATED_AMOUNT DESC; 

您可以使用as alias_name_here或只是alias_name_here - SQL Server允許任何語法。

0

必須在你的「表」
我給的是與「爲T

SELECT DISTINCT HOLDER_CODE, CALCULATED_AMOUNT 
FROM (
    SELECT DA.HOLDER_CODE, 
     ROUND(FAB.AMOUNT * FCE.EXCHANGE_RATE,0) AS CALCULATED_AMOUNT, 
     FAB.BALANCE_DATE_ID as FAB_DATE, 
     MAX(FAB.BALANCE_DATE_ID) OVER (PARTITION BY DA.HOLDER_CODE) as MAX_DATE_BALANCE 
    FROM DIM_ACCOUNT DA 
     JOIN FACT_AS_BALANCE FAB ON FAB.ACCOUNT_ID = DA.ID 
     JOIN DIM_AS_CHARACTERISTICS DAC ON DAC.ID = FAB.BALANCE_TYPE_ID 
     LEFT JOIN FACT_CURRENCY_EXCHANGE FCE ON FCE.FROM_CURRENCY_ID = FAB.CURRENCY_ID 
    WHERE DAC.BALANCE_CLOSING_FLAG = 'Y' 
    AND TO_CURRENCY_ID = ( 
SELECT DC.ID FROM DIM_CURRENCY DC 
WHERE DC.IS_DEFAULT_CURRENCY = 'Y') 
    AND FAB.AMOUNT > 0 
) as T 
WHERE FAB_DATE = MAX_DATE_BALANCE 
ORDER BY CALCULATED_AMOUNT DESC;