如何在没有内部子查询的情况下创建sum列?

时间:2012-08-14 14:47:53

标签: sql sql-server sql-server-2008

我正在使用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子查询。

如果没有它,是否有一种优雅的方法来实现有条件求和的列?

这里有哪些聚合命令(如果有的话),以及如何应用这些命令?

6 个答案:

答案 0 :(得分:4)

试试这个:

SELECT *, SUM(CASE WHEN condition = 1 THEN value END) OVER() SumOfConditionalValues
FROM @t

答案 1 :(得分: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

编辑:不知道你是否希望每一行显示condition = 1的行总和,但是如果你只是将join子句更改为:

LEFT JOIN MyTable JoinedMyTable ON JoinedMyTable.Condition = 1

答案 2 :(得分:0)

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

  select id, sum(case when condition=1 then value else 0 end) group by id..etc

答案 3 :(得分:0)

Declare @sum int
SELECT @sum=SUM(value) FROM @t WHERE condition = 1
select *,@sum from yourtable

答案 4 :(得分: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 

答案 5 :(得分: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

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