Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 selecting same column twice

Author  Topic 

nibbles70
Starting Member

2 Posts

Posted - 2014-02-02 : 15:14:29
How can I easily select a derived column again in the same query?

Select
COL1,
COL2,
<complex_functions> as COL3,
COL3 / COL2 as COL4
from...

nibbles70
Starting Member

2 Posts

Posted - 2014-02-02 : 15:25:01
Example :

select 1 as A,
2 as B,
3 as C
,B * C as D;

Msg 207, Level 16, State 1, Line 4
Invalid column name 'B'.
Msg 207, Level 16, State 1, Line 4
Invalid column name 'C'.
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2014-02-02 : 22:55:01
[code]select COL1, COL2, COL3, COL3 / COL2 as COL4
from
(
select COL1, COL2, COL3
from . . .
) as D[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-02-03 : 04:24:52
quote:
Originally posted by nibbles70

Example :

select 1 as A,
2 as B,
3 as C
,B * C as D;

Msg 207, Level 16, State 1, Line 4
Invalid column name 'B'.
Msg 207, Level 16, State 1, Line 4
Invalid column name 'C'.


in this case you can directly do
2 * 3 AS D
however if its a really complicated expression you need to use derived table approach as shown by Tan

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2014-02-03 : 06:07:12
Derived columns can be accessed using derived table although it can be directly access in ORDER BY clause



Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -