我在Oracle中编写了这个查询,并希望在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;
但是当我运行它时,我得到以下异常:
错误:关键字' WHERE'附近的语法不正确。 SQLState:S0001 ErrorCode:156
所以我猜,它是最后一个where子句,它表明了这一点。有什么不对,应该是什么?
答案 0 :(得分: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允许使用任何一种语法。
答案 1 :(得分:0)
你必须在你的“牌桌”上给出一个名字
我给的是“ as 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;