2

I am using following query to do this

select (Col_A + Col_B) Foo,
       (Col_C + Col_D) Bar,
       (Col_A + Col_B + Col_C + Col_D) FooBar from Table1

But is there a way like to do like this

select (Col_A + Col_B) Foo,
       (Col_C + Col_D) Bar,
       (Foo + Bar) FooBar from Table1

it gives Error

'Invalid Column Foo'
'Invalid Column Bar'

How to solve this?

1

3 Answers 3

3

Partial solution is to use with construction:

with query as (
  select (Col_A + Col_B) Foo,
         (Col_C + Col_D) Bar
    from Table1)

select Foo,
       Bar,
       Foo + Bar
  from query
Sign up to request clarification or add additional context in comments.

1 Comment

@Nikhil Agrawal: it has name CTE in MS SQL, but "with" works (with some restrictions) in Oracle, Postgre as well
0

Afaik those columns you're referring to don't exist by those names yet.

You can of course try the following instead:

SELECT *, (Foo + Bar) FooBar
FROM (select (Col_A + Col_B) Foo,
       (Col_C + Col_D) Bar
     from Table1) SRC

Comments

0

SQL parses the FROM before SELECT so you need to add your alias in your FROM clause

SELECT Foo
      ,Bar
      ,Foo + Bar
FROM Table1
     CROSS APPLY (
         SELECT Col_A + Col_B AS Foo
               ,Col_C + Col_D AS Bar
     ) AS CA1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.