I'm using SQL Server 2008 R2
I have a complex query which I need to have a conditionally summed column for it.
Here is a simplified version of my query and results:
DECLARE @t TABLE (id int, condition int, value int);
INSERT INTO @t
VALUES (1,1,12), (2,0,88), (3,1,11)
SELECT
*,
(SELECT SUM(value) FROM @t WHERE condition = 1) as SumOfConditionalValues
FROM @t
Here are the results of this query"
id condition value SumOfConditionalValues
1 1 12 23
2 0 88 23
3 1 11 23
I can't afford the SumOfConditionalValues
sub query.
Is there an elegant way to achieve the conditionally summed column without it?
Which aggregate commands are suitable here, if any, and how do I apply these?