I have a table with columns A, B and C, and I want to select from that table, but with some additional fields computed from A, B and C and other computed fields. For example:
- D = A * B + C
- E = 2 * D + 4 * A
- F = D * D * E
I thought I could solve that like this:
select A, B, C, (A * B + C) as D, (2 * D + 4 * A) as E, (D * D * E) as F
from Table
But this results in an error: SQL Server won't let me use D in the expression for E.
I have come up with two ways of working around this:
- I expand the uses of D in E and F and the uses of D and E in F to their full definitions, e.g.
(2 * (A * B + C) + 4 * A) as E, ((A * B + C) * (A * B + C) * (2 * (A * B + C) + 4 * A)) as F
Use subqueries like so:
select A, B, C, D, E, (D * D * E) as F from ( select A, B, C, D, (2 * D + 4 * A) as E from ( select A, B, C, (A * B + C) as D ) as UpToD ) as UpToE
Neither solution is satisfactory: in case 1, the query becomes unmanagably long, and whenever I change the way a field is computed, all fields that depend on it need to be updated. Recursively. In case 2, the situation is a little better, but it still feels awkward to create a subquery for every new field I want to compute and I need to repeatedly list all field names.
What's the best way to express this query?
Thanks in advance!