1

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?

4

6 に答える 6

4

Try this:

SELECT *, SUM(CASE WHEN condition = 1 THEN value END) OVER() SumOfConditionalValues
FROM @t
于 2012-08-14T14:55:36.440 に答える
1

See here: http://sqlfiddle.com/#!3/1abea/1

Use a self join:

CREATE TABLE MyTable (id int, condition int, value int); 

INSERT INTO MyTable 
VALUES (1,1,12), (2,0,88), (3,1,11)

SELECT
  MyTable.id,
  MyTable.Condition,
  MyTable.value,
  SUM(JoinedMyTable.Value)
FROM
  MyTable
  LEFT JOIN MyTable JoinedMyTable ON MyTable.condition = JoinedMyTable.Condition
GROUP BY
  MyTable.id,
  MyTable.Condition,
  MyTable.value

EDIT: Don't know if you want every row to show the sum of rows where condition = 1, but if you do just change the join clause to be:

LEFT JOIN MyTable JoinedMyTable ON JoinedMyTable.Condition = 1
于 2012-08-14T15:07:35.640 に答える
0

I believe what you are looking for is the "CASE' statement...Very powerful, for example:

  select id, sum(case when condition=1 then value else 0 end) group by id..etc
于 2012-08-14T14:51:51.717 に答える
0
Declare @sum int
SELECT @sum=SUM(value) FROM @t WHERE condition = 1
select *,@sum from yourtable
于 2012-08-14T15:01:19.677 に答える
0

You can bring the results aggregated by condition:

DECLARE @t TABLE (id int, condition int, value int); 
INSERT INTO @t VALUES (1,1,12), (2,0,88), (3,1,11)
SELECT *, 
sum(value) over (partition by condition) as SumOfConditionalValues 
FROM @t 
于 2012-08-14T15:07:03.950 に答える
0

I think this is what you want:

SELECT id, condition, value,   
      SUM(CASE WHEN condition = 1 THEN value_at_1 END) OVER() SumOfConditionalValues
FROM (select *,
             (case when condition = 1 then value end) as value_at_1
      from @t
     ) t

You need a "conditional value", which you can create in a subquery.

于 2012-08-14T15:10:38.390 に答える