macunte
macunte

Reputation: 465

SQL to reference another column's value

I would like to know how to reference the values from a column in my query for use in a adjacent column having a different column name. As you can see, I just don't see that it is necessary to place the case statement shown below twice in my code.

select acct, name, address,
case when pterm||' '||ptermc = '0' then date(digits(matdt7)) 
    when pterm||' '||ptermc = '1 D' then curdate() 
    when pterm||' '||ptermc = '1 M' then date(digits(prevd7))+30 day
    when pterm||' '||ptermc = '3 M' then date(digits(prevd7))+90 day
    when pterm||' '||ptermc = '6 M' then date(digits(prevd7))+180 day
    when pterm||' '||ptermc = '12 M' then date(digits(prevd7))+365 day
    else null end as "Next Repricing Date",

I would like the section below to just insert the values from the case section above.

phone, value from Next Repricing Date AS "balloon date"
from my.table

Upvotes: 1

Views: 7765

Answers (1)

Richthofen
Richthofen

Reputation: 2086

It isn't possible to reference an aliased column in the same select statement. You could use a subquery as so

SELECT q.ColA as "Next Repricing", q.ColA as "Balloon Date" FROM
(select acct, name, address,
case when pterm||' '||ptermc = '0' then date(digits(matdt7)) 
when pterm||' '||ptermc = '1 D' then curdate() 
when pterm||' '||ptermc = '1 M' then date(digits(prevd7))+30 day
when pterm||' '||ptermc = '3 M' then date(digits(prevd7))+90 day
when pterm||' '||ptermc = '6 M' then date(digits(prevd7))+180 day
when pterm||' '||ptermc = '12 M' then date(digits(prevd7))+365 day
else null end as ColA, ...) As q

Another option would be to write your own User Defined function if the case statement is a common transform.

Upvotes: 1

Related Questions