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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With