我想做这样的事情:
SELECT round(100*(col_a - col_b)/col_a, 1) as Foo, Foo - col_c as Bar
FROM my_table
WHERE...;
但是,我收到一条错误消息,指出Foo
未知。由于Foo是从一堆其他列的某些计算得出的,所以我不想再为Bar
重复该公式。任何解决方法?
答案 0 :(得分:8)
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;
答案 1 :(得分:3)
我通常会使用子查询处理此问题:
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 ...
如果你有SQL Server,那么CTE可以实现同样的目标。