Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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')

like image 589
PowerUser Avatar asked Feb 23 '23 03:02

PowerUser


1 Answers

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
like image 158
Lamak Avatar answered Feb 25 '23 06:02

Lamak