简体   繁体   中英

How to create SQL alias outside of SELECT statement

I created a query with a lot of calculations and cannot figure out how to store a calculated value to a variable without including in within the SELECT statement. Example:

SELECT (VAL_1 + VAL_2) as CALC_1, (CALC_1 + VAL_3) as CALC_2 FROM MY_TABLE

I can use CALC_1 alias in additional SELECT's. How do I use alias if i did NOT want to display/SELECT it? The below gave me an Invalid Query Error.

DECLARE @CALC_1 INTEGER
SET @CALC_1 = VAL_1 + VAL_2
SELECT @CALC_1, @CALC_1 + VAL_3
FROM MY_TABLE

If I understand correctly you need to nest it in a Derived Table:

SELECT (CALC_1 + VAL_3) as CALC_2 
FROM 
 (
   SELECT (VAL_1 + VAL_2) as CALC_1 
   FROM MY_TABLE
 ) as dt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM