September 19, 2003 at 11:37 pm
Hi fellow developers,
I have a T-SQL question. Is it possible to write a query in such a way that a calculated column can be reused in a subsequent column below in a select statement? For example:
SELECT (1 + 2) AS [first],
(3 + 4) AS [second],
[first] + [second] AS [total]
Of course, the above example would give me an invalid column name error. How can I reuse the [first] column and the [second] column for the [total] without having to do a
1 + 2 + 3 + 4
recalculation.
Thanks a lot for you help.
Chiby
September 20, 2003 at 12:31 am
Hi Chiby,
How about trying something like this...
SELECT [first], [second], [first] + [second] AS [Total]
FROM ( SELECT (1 + 2) AS [first], (3 + 4) AS [second]) AS NewTbl
HTH...
Sachin
Regards,
Sachin Dedhia
September 20, 2003 at 12:51 am
Thanks a lot Sachin
That works!
I also found out another way of doing this:
DECLARE @First INT
DECLARE @Second INT
SELECT @First = 1 + 2,
@Second = 3 + 4
SELECT @First AS [First],
@Second AS [Second],
@First + @Second AS [Total]
Thanks a lot again, I really appreciate it.
Chiby
quote:
Hi Chiby,
How about trying something like this...
SELECT [first], [second], [first] + [second] AS [Total]
FROM ( SELECT (1 + 2) AS [first], (3 + 4) AS [second]) AS NewTbl
HTH...
Sachin
September 20, 2003 at 1:11 am
There is always another way...
🙂
Regards,
Sachin Dedhia
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply