“表”查询中的一个简单的Select x,y,z在select中包含“ Case when”。
此字段的结尾为“结束为'结果字段'”。
我想在另一个命令中使用该“结果字段”作为同一SELECT命令(Dateadd命令)的一部分。
SELECT
PositionDate,
ISIN,
Issuer,
FirstCouponDate,
TermLength,
TermUnit,
CASE
WHEN TermUnit = 'Years' THEN 'year'
WHEN TermUnit = 'Months' THEN 'month'
END AS 'TermUnitRenamed',
DATEADD(TermUnitRenamed, TermLength, FirstCouponDate),
FROM
GIBDataWarehouse.dbo.vw_Positions
答案 0 :(得分:0)
基于您提供的信息的两个建议:在您的ELSE
语句中添加一个CASE
默认值;然后,将此查询嵌套在后续查询中,以便您可以引用新创建的字段。
select
*
, case
when TermUnitRenamed = 'year' then DateAdd(year, TermLength, FirstCouponDate)
when TermUnitRenamed = 'month' then DateAdd(month, TermLength, FirstCouponDate)
when TermUnitRenamed = 'day' then DateAdd(day, TermLength, FirstCouponDate)
end as newDate
from (
select
PositionDate
, ISIN
, Issuer
, FirstCouponDate
, TermLength
, TermUnit
, case
when TermUnit = 'Years' then 'year'
when TermUnit = 'Months' then 'month'
else 'day' -- assumes default 'day' unit
end AS TermUnitRenamed
from GIBDataWarehouse.dbo.vw_Positions
) x
当然,您只需在原始查询本身中应用CASE
和DATEADD
逻辑,如果不需要TermUnitRenamed
就可以完全避免嵌套还有什么。
select
PositionDate
, ISIN
, Issuer
, FirstCouponDate
, TermLength
, TermUnit
, case
when TermUnit = 'Years' then DateAdd(year, TermLength, FirstCouponDate)
when TermUnit = 'Months' then DateAdd(month, TermLength, FirstCouponDate)
else then DateAdd(day, TermLength, FirstCouponDate) -- assumes default 'day' unit
end AS newDate
from GIBDataWarehouse.dbo.vw_Positions