我正在使用以下查询来执行此操作
select (Col_A + Col_B) Foo,
(Col_C + Col_D) Bar,
(Col_A + Col_B + Col_C + Col_D) FooBar from Table1
但有没有像这样做的方式
select (Col_A + Col_B) Foo,
(Col_C + Col_D) Bar,
(Foo + Bar) FooBar from Table1
它给出错误
'Invalid Column Foo'
'Invalid Column Bar'
如何解决这个问题?
答案 0 :(得分:3)
部分解决方案是使用with
构造:
with query as (
select (Col_A + Col_B) Foo,
(Col_C + Col_D) Bar
from Table1)
select Foo,
Bar,
Foo + Bar
from query
答案 1 :(得分:0)
Afaik那些你所指的那些专栏尚未被这些名称存在。
您当然可以尝试以下方式:
SELECT *, (Foo + Bar) FooBar
FROM (select (Col_A + Col_B) Foo,
(Col_C + Col_D) Bar
from Table1) SRC
答案 2 :(得分:0)
SQL在SELECT之前解析FROM,因此您需要在FROM子句中添加别名
SELECT Foo
,Bar
,Foo + Bar
FROM Table1
CROSS APPLY (
SELECT Col_A + Col_B AS Foo
,Col_C + Col_D AS Bar
) AS CA1