1

我正在使用 SQL Server 2008 R2

我有一个复杂的查询,我需要一个有条件的求和列。

这是我的查询和结果的简化版本:

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 

这是此查询的结果"

id  condition   value   SumOfConditionalValues
1   1           12      23
2   0           88      23
3   1           11      23

我买不起SumOfConditionalValues子查询。

没有它有没有一种优雅的方法来实现条件求和列?

哪些聚合命令适用于此处(如果有),我该如何应用这些命令?

4

6 回答 6

4

尝试这个:

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

见这里:http ://sqlfiddle.com/#!3/1abea/1

使用自联接:

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

编辑:不知道您是否希望每一行都显示条件 = 1 的行的总和,但如果您确实将连接子句更改为:

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

您可以带来按条件聚合的结果:

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
Declare @sum int
SELECT @sum=SUM(value) FROM @t WHERE condition = 1
select *,@sum from yourtable
于 2012-08-14T15:01:19.677 回答
0

我认为这就是你想要的:

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

您需要一个“条件值”,您可以在子查询中创建它。

于 2012-08-14T15:10:38.390 回答
0

我相信您正在寻找的是“CASE”声明......非常强大,例如:

  select id, sum(case when condition=1 then value else 0 end) group by id..etc
于 2012-08-14T14:51:51.717 回答