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 2005 Forums
 Transact-SQL (2005)
 How to reference new column in select statement

Author  Topic 

timlisten
Starting Member

26 Posts

Posted - 2012-06-16 : 15:22:37
Hi, Let's say I have a table with col1 and col2 and a statement like the this

select (col1+col2) as col_new, (col_new+col1) as col_new2,....
FROM table

why the sql cannot recognized the newly computed col_new? I believe in mysql that works fine. In my situation, the col_new is much more complicated than the simple col1+col2, but I want to reuse that as a standing point instead of recalculating for every new column. Is there a direct way of doing this without using derive query because I have many calculated columns on the fly?

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-17 : 11:47:26
[code]
select col_new,(col_new+col1) as col_new2,
from
(
select (col1+col2) as col_new, ....
FROM table
)t
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

timlisten
Starting Member

26 Posts

Posted - 2012-06-18 : 13:57:16
Hi visakh16, I understand you can do that, but the problem is I have too many computations that I need to do. Each derive from the other, if I have to add a new layer to each the code just becomes very confusing.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-18 : 14:50:59
quote:
Originally posted by timlisten

Hi visakh16, I understand you can do that, but the problem is I have too many computations that I need to do. Each derive from the other, if I have to add a new layer to each the code just becomes very confusing.


you've to either add a new layer or repeat calculation as it is. You cant use aliases directly in same level

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

timlisten
Starting Member

26 Posts

Posted - 2012-06-18 : 20:50:28
thanks, I guess I will have to do it this way if there is no other way around.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-18 : 22:48:58
wc

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -