Reputation: 1245
I want to do something like this:
SELECT round(100*(col_a - col_b)/col_a, 1) as Foo, Foo - col_c as Bar
FROM my_table
WHERE...;
However, I get an error saying Foo
is unknown. Since Foo is derived from some calculations on a bunch of other columns, I don't want to repeat the formula again for Bar
. Any work-arounds?
Upvotes: 8
Views: 2862
Reputation: 1815
I would usually handle this with a sub-query:
SELECT Foo, Foo - col_c as Bar
FROM (
SELECT round(100*(col_a - col_b)/col_a, 1) as Foo, col_c
FROM my_table
WHERE ...
)
WHERE ...
If you've got SQL Server, a CTE achieves much the same thing.
Upvotes: 3
Reputation: 5714
SELECT Foo, Foo - col_c as Bar
from (
SELECT round(100*(col_a - col_b)/col_a, 1) as Foo, col_c
FROM my_table
WHERE...
) t;
Upvotes: 9