SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 selecting same column twice
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

nibbles70
Starting Member

2 Posts

Posted - 02/02/2014 :  15:14:29  Show Profile  Reply with Quote
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 - 02/02/2014 :  15:25:01  Show Profile  Reply with Quote
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)

Singapore
17438 Posts

Posted - 02/02/2014 :  22:55:01  Show Profile  Reply with Quote
select COL1, COL2, COL3, COL3 / COL2 as COL4
from
(
    select COL1, COL2, COL3
    from   . . .
) as D



KH
Time is always against us

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52249 Posts

Posted - 02/03/2014 :  04:24:52  Show Profile  Reply with Quote
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

India
22713 Posts

Posted - 02/03/2014 :  06:07:12  Show Profile  Send madhivanan a Yahoo! Message  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000