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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With