How to use calculated field in another field of the same query

守給你的承諾、 提交于 2019-12-10 17:12:26

问题


I have a select query with a few dozen fields. "FieldA" is a Case statement about 10 rows tall. I now have to make a "FieldB" which uses the same Case statement plus a constant.

With my current knowledge of sql-server, I'd have to repeat that Case statement twice (once for FieldA and once for FieldB). To clean up my code, how can I use fieldA in the calculation of FieldB?

Ideally, my code would look something like this:

Select
    Case ...
        When ... then ...
        When ... then ...
        When ... then ...
    End                     as FieldA,
    FieldA + 1              as FieldB
From TblSource

(I know that one option is to dump the data into a temporary table, then update that temp table. But that kind of defeats the concept of 'simplifying')


回答1:


Do it like this:

;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



回答2:


@Johnny_D

There's always the possibility of using the following

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


来源:https://stackoverflow.com/questions/8511982/how-to-use-calculated-field-in-another-field-of-the-same-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!