Sum和Group By Clause

时间:2013-03-24 10:48:06

标签: sql-server sql-server-2008

我有一个如下所示的表

Name         Id         Sub1        Sub2 
Raj          1           75          76   
Ramesh       2           85          58   
Sekhar       3           65          55   
Siddharth    4           95          85    
Raj          1           52          75   
Sekhar       3           97          95   
Siddharth    5           78          85   

我需要输出如下

Name         Id       Sub1     Sub2 
Raj          1         127      151  
Ramesh       2          85       58   
Sekhar       3         162      150    
Siddharth    4          95       85  
Siddharth    5          78       85   

那就是我需要在主题列和ID列中添加标记的总和。我需要显示Name,但不应该包含在GroupBy子句中。 我该如何编写查询以获得所需的结果?提前谢谢。

3 个答案:

答案 0 :(得分:2)

试试这个: -

with cte as 
(  Select row_number() over(partition by a.id order by a.ID) rn,
   a.name,a.id , b.sum1, b.sum2  from
   sample a
   inner join 
  ( Select id,sum(sub1) Sum1,sum(sub2) as sum2 
    from Sample 
    group by id)b
  on a.id=b.id
)
Select name,id,sum1,sum2 from cte where rn=1

或者您还Sum

使用OverSubquery子句
 Select *
 from 
 (
  Select name,id,sum(sub1) over (partition by id) sub1,
  sum(sub2) over(partition by id) sub2,
  row_number() over(partition by Id order by id) rn
  from sample
 ) s
 where rn=1 
 order by s.name

SQLFIDDLE演示

答案 1 :(得分:0)

似乎在完成所有澄清后,它真的就像:

select Name
  , Id
  , Sub1 = sum(Sub1)
  , Sub2 = sum(Sub2)
from MyTable
group by Name, Id
order by Id

SQL Fiddle with demo

答案 2 :(得分:0)

如果您需要从group by子句中排除Name,假设您的ID是唯一标识符,并且只将ID分配给1个名称​​,则汇总Name使用MAX()

SELECT
    MAX(Name) AS [Name]
   ,Id
   ,SUM(Sub1) AS [Sub1]
   ,SUM(Sub2) AS [Sub2]

FROM
    MyTable

GROUP BY
    Id

ORDER BY
    Id