我有几十个字段的选择查询。 “FieldA”是一个大约10行高的Case语句。我现在必须创建一个“FieldB”,它使用相同的Case语句加一个常量。
根据我目前对sql-server的了解,我必须重复两次Case语句(一次用于FieldA,一次用于FieldB)。要清理我的代码,如何在FieldB的计算中使用fieldA?
理想情况下,我的代码看起来像这样:
Select
Case ...
When ... then ...
When ... then ...
When ... then ...
End as FieldA,
FieldA + 1 as FieldB
From TblSource
(我知道一个选项是将数据转储到一个临时表中,然后更新那个临时表。但是这种方法违背了“简化”的概念)
答案 0 :(得分:5)
这样做:
;WITH YourCTE AS
(
Select
Case ...
When ... then ...
When ... then ...
When ... then ...
End as FieldA
From TblSource
)
SELECT FieldA, FieldA + 1 AS FieldB, FieldA + 2 AS FieldC ....
FROM YourCTE
答案 1 :(得分:2)
@Johnny_D
总是有可能使用以下
Select tbl.*,tbl.FieldA+1 as FieldB, tbl.FieldA+2 as FieldC from
(
Select
Case ...
When ... then ...
When ... then ...
When ... then ...
End as FieldA
From TblSource
) as tbl