如果我在SELECT子句中使用别名,我该如何引用该别名?

时间:2011-08-19 10:35:51

标签: sql

我想做这样的事情:

SELECT round(100*(col_a - col_b)/col_a, 1) as Foo, Foo - col_c as Bar
FROM my_table
WHERE...;

但是,我收到一条错误消息,指出Foo未知。由于Foo是从一堆其他列的某些计算得出的,所以我不想再为Bar重复该公式。任何解决方法?

2 个答案:

答案 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可以实现同样的目标。