Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid repeating a calculated expression multiple times in the same select?

How can I use a calculated column multiple times in the same select without repeating the expression and without using common table expressions or complex subselects?

DECLARE @T TABLE ( NUM1 INT,NUM2 INT)
INSERT INTO @T VALUES (2,3);
INSERT INTO @T VALUES (5,7);
INSERT INTO @T VALUES(32,3);
INSERT INTO @T VALUES(6,8);

SELECT (NUM1+NUM2) [ADD], [ADD]*2, [ADD]/2,* FROM @T

Is there any way to solve this in SQL Server 2005?

like image 694
arturn Avatar asked Nov 18 '11 11:11

arturn


2 Answers

You can use cross apply

SELECT T2.[ADD],
       T2.[ADD]*2,
       T2.[ADD]/2
FROM @T AS T1
  CROSS APPLY (SELECT T1.NUM1+T1.NUM2) AS T2([ADD])

or a CTE

WITH C AS
(
  SELECT NUM1+NUM2 AS [ADD]
  FROM @T
)
SELECT [ADD],
       [ADD]*2,
       [ADD]/2
FROM C

or a subquery (also known as a derived table)

SELECT T.[ADD],
       T.[ADD]*2,
       T.[ADD]/2
FROM (
       SELECT NUM1+NUM2 AS [ADD]
       FROM @T
     ) AS T

It is not possible to use the column alias in the same field list as it is declared.

like image 145
Mikael Eriksson Avatar answered Nov 18 '22 20:11

Mikael Eriksson


You could use a derived table to accomplish this:

SELECT 
     *,
     [ADD]*2,
     [ADD]/2
FROM
(
     SELECT (NUM1+NUM2) AS [ADD], NUM1, NUM2 FROM @T 
) AS A
like image 42
Doozer Blake Avatar answered Nov 18 '22 20:11

Doozer Blake