计算字段的SUM()

时间:2012-01-20 01:44:32

标签: sql sql-server sum aggregate alias

我有这个问题:

select 
C.One
,C.Two
,C.Three
,C.Four

from mytable C

where C.One = 11052 and C.Three = 97734

返回:

One  |Two | Three  | Four
11052   2   97734   4
11052   2   97734   4
11052   2   97734   4
11052   2   97734   4
11052   2   97734   4
11052   2   97734   4
11052   2   97734   4
11052   2   97734   4
11052   2   97734   4
11052   2   97734   4
11052   1   97734   4
11052   1   97734   4
11052   1   97734   4
11052   1   97734   4
11052   1   97734   4
11052   1   97734   4
11052   1   97734   4
11052   1   97734   4
11052   1   97734   4
11052   1   97734   4
11052   3   97734   4
11052   3   97734   4
11052   3   97734   4
11052   3   97734   4
11052   3   97734   4
11052   3   97734   4
11052   3   97734   4
11052   3   97734   4
11052   3   97734   4
11052   3   97734   4
11052   4   97734   4
11052   4   97734   4
11052   4   97734   4
11052   4   97734   4
11052   4   97734   4
11052   4   97734   4
11052   4   97734   4
11052   4   97734   4
11052   4   97734   4
11052   4   97734   4
11052   5   97734   4
11052   5   97734   4
11052   5   97734   4
11052   5   97734   4
11052   5   97734   4
11052   5   97734   4
11052   5   97734   4
11052   5   97734   4
11052   5   97734   4
11052   5   97734   4

很抱歉长粘贴,因为你可以看到每一行重复10次,每个“第二列”值(10倍,1,2,3,4,5)总行数50。

2)

如果写了这个:

select 
C.One
,C.Two
,C.Three
,C.Four
,sum(c.Four) as 'Sum'

from mytable C

where C.One = 11052 and C.Three = 97734
group by C.One, C.Two,C.Three , C.Four

导致:

One  | Two | Three  | Four  |  Sum
11052   1       97734   4   40
11052   2       97734   4   40
11052   3       97734   4   40
11052   4       97734   4   40
11052   5       97734   4   40

Sum应该是20(4 + 4 + 4 + 4 + 4)但它是40'导致在previuos查询中10次重复4次。 (上图)。

我最终应该

One  | Two | Three  | Four  |  Sum
11052   1       97734   4   20
11052   2       97734   4   20
11052   3       97734   4   20
11052   4       97734   4   20
11052   5       97734   4   20

我应该怎么做才能解决这个问题并获得20而不是40?希望很清楚。谢谢你的时间。

3 个答案:

答案 0 :(得分:1)

您可以使用子查询完成此操作:

select a.One,a.Two,a.Three,a.Four,sum(a.Four) as 'Sum'
from (select C.One,C.Two,C.Three,C.Four
  from mytable C
  where C.One = 11052 and C.Three = 97734
  group by C.One, C.Two,C.Three , C.Four) a

答案 1 :(得分:0)

试试这个:

 select 
      DISTINCT C.Two
      ,C.One
      ,C.Three
      ,C.Four
      ,sum(c.Four) as 'Sum'

 from mytable C
 where C.One = 11052 and C.Three = 97734
 group by  C.Two,C.One,C.Three,C.Four

答案 2 :(得分:0)

我假设您正在使用SQL Server 2008及以上,如果没有请注释 您正尝试从myTable获取5个唯一行;我们称之为tempResult 然后,对于要添加列的所有唯一行 此列是FourtempResult的总和 每行都会有相同的值

select
  One, 
  Two, 
  Three, 
  Four, 
  sum(Four) over (order by One,Two,Three,Four asc) as SumAll
from
(
  select distinct
    C.One,
    C.Two,
    C.Three,
    C.Four,
  from mytable C  
  where 
    C.One = 11052 and 
    C.Three = 97734 
) g