Victor Ng
Victor Ng

Reputation: 71

Deriving new column using new column

Normally we can build new columns in Select statements. Is it possible to derive new columns out of new columns in Select statements?

For example,

Select 1+2 A

This gives us a table with column A and the value 3 in 1 row.

Can I build a new column B that is based on A?

For example,

Select 1+2 A, 4+A B

Unfortunately the above will result in "Invalid column name A".

Upvotes: 1

Views: 1170

Answers (3)

Safi
Safi

Reputation: 1

No need to wrap it up in 5 different subqueries / derived tables / CTEs.

Just write the full logic for each derived columns.

select 2-1 as A, 4+ (2-1) as B, 5* (4+(2-1)) as C

Upvotes: 0

Ivancito
Ivancito

Reputation: 169

Use a temporary table

Select 1+2 as A
INTO #TEMPORARY_TABLE
FROM TABLE

SELECT 4+A as B
FROM #TEMPORARY_TABLE

Upvotes: 1

dougp
dougp

Reputation: 3089

Use a subquery.

select 4 + A as 'B'
from (
    select 1 + 2 as 'A'
) q

Upvotes: 1

Related Questions