我在Oracle中有一个SQL查询,该查询具有使用case语句计算的列。我想使用新创建的列作为第二个计算列的输入。请在下面查看我的代码。
当我尝试运行此代码时,出现错误“ PAYER_TYPE”:无效的标识符。那么,在第二列中是否可以使用“ PAYER_TYPE”值?
SELECT
CASE
WHEN TYP IN ('Swap', 'Ton')
THEN
CASE
WHEN INDX_PAY = 'FIXED'
THEN 'FIXED'
ELSE 'FLAT'
END
END AS PAYER_TYPE,
CASE
WHEN TYPE = 'Swaption'
THEN
CASE
WHEN PAYER_TYPE = 'FIXED'
THEN PAY_LEG
ELSE REC_LEG
END
ELSE 0
END AS STRIKE
FROM Hedge.Details
答案 0 :(得分:0)
一个简单的选项是一个内联视图,或者-最近-一个CTE(公用表表达式),又称WITH分解子句。像这样:
with your_data as
(select case when ... then ...
when ... then ...
end paper_type --> PAPER_TYPE gets its value here ...
from some_table
where ...
)
select case when y.paper_type = 'A' then ... --> ... and is reused here
when y.paper_type = 'B' then ...
end result
from your_data y
答案 1 :(得分:0)
您可以在子查询中生成该列PAYER_TYPE,然后在外部使用
SELECT
PAYER_TYPE,
CASE
WHEN TYP = 'Swaption'
THEN
CASE
WHEN PAYER_TYPE = 'FIXED'
THEN 'PAY_LEG'
ELSE 'REC_LEG'
END
ELSE '0'
END AS STRIKE
FROM
(
WITH Details(TYP,INDX_PAY) AS
(
SELECT 'Swap', 'FIXED' FROM DUAL UNION ALL
SELECT 'Ton' , 'FIX' FROM DUAL
)
SELECT
CASE
WHEN TYP IN ('Swap', 'Ton')
THEN
CASE
WHEN INDX_PAY = 'FIXED'
THEN 'FIXED'
ELSE 'FLAT'
END
END PAYER_TYPE,
TYP
FROM Details
)
PAYER_TYPE STRIKE
---------- ------
FIXED 0
FLAT 0
答案 2 :(得分:0)
您收到错误,因为PAYER_TYPE不是Hedge.Details中的列。如果您确实想使用PAYER_TYPE,请尝试以下操作:
SELECT
C1.PAYER_TYPE,
CASE
WHEN C1.TYPE = 'Swaption'
THEN
CASE
WHEN C1.PAYER_TYPE = 'FIXED'
THEN C1.PAY_LEG
ELSE C1.REC_LEG
END
ELSE 0
END AS STRIKE
FROM
(
SELECT
CASE
WHEN TYP IN ('Swap', 'Ton')
THEN
CASE
WHEN INDX_PAY = 'FIXED'
THEN 'FIXED'
ELSE 'FLAT'
END
END AS PAYER_TYPE,
TYPE,
PAY_LEG,
REC_LEG
FROM Hedge.Details
) AS C1
您最好的选择是保持简单,而不使用如下所示的子查询方法:
SELECT
CASE
WHEN TYP IN ('Swap', 'Ton')
THEN
CASE
WHEN INDX_PAY = 'FIXED'
THEN 'FIXED'
ELSE 'FLAT'
END
END AS PAYER_TYPE,
CASE
WHEN TYPE = 'Swaption'
THEN
CASE
WHEN TYP IN ('Swap', 'Ton') AND INDX_PAY = 'FIXED'
THEN PAY_LEG
ELSE REC_LEG
END
ELSE 0
END AS STRIKE
FROM Hedge.Details