There seems to be some important information missing from your question. If all you really want is the FinalCalcColRate
for each row in your Rates
table, then you can do it one step like @scsimon suggested in his/her answer:
select
r.*,
FinalCalcColRate = case when r.AnnualCost is null then 0 else r.AnnualCost / 12 * 100000 end
from
dbo.Rates r;
Or a similar implementation using coalesce
(or isnull
in SQL Server; see this question for details on the differences):
select
r.*,
FinalCalcColRate = coalesce(r.AnnualCost / 12 * 100000, 0)
from
dbo.Rates r;
However, one difference between @scsimon's query and your original is that the former outputs only the final calculated value while the latter also yields all of the intermediate values. It's not clear from your question whether consumers of this query will require those values or not. If they will, then you can include them simply enough:
select
r.*,
CalcColRate = coalesce(r.AnnualCost / 12, 0),
NewCalcColRate = coalesce(r.AnnualCost / 12 * 100, 0),
FinalCalcColRate = coalesce(r.AnnualCost / 12 * 100000, 0)
from
dbo.Rates r;
There is some repetition of logic here—for instance, if you were to ever change the definition of CalcColRate
, you would also have to manually change the expressions for NewCalcColRate
and FinalCalcColRate
—but it's small enough that I doubt it's worth worrying about. Nonetheless, if the construction in your original query was motivated by a desire to avoid such repetition, you can refactor the query to use CTEs instead of nested queries:
with CalcCTE as
(
select
r.*,
CalcColRate = coalesce(r.AnnualCost / 12, 0)
from
dbo.Rates r
),
NewCalcColCTE as
(
select
c.*,
NewCalcColRate = c.CalcColRate * 100
from
CalcCTE c
)
select
n.*,
FinalCalcColRate = n.NewCalcColRate * 1000
from
NewCalcColCTE n;
This is obviously longer and arguably more difficult to understand than my previous query that defined all the values independently, but it does have the advantage that each step is built atop the last, and the CTE formulation tends to be a lot more readable than the equivalent set of nested queries since the steps are written in the order in which they're evaluated, whereas with a nested query you have to find the innermost point and work outward, which can get confusing in a hurry.