1

我有一个如下所示的表格

名称 ID Sub1 Sub2
拉吉 1 75 76   
拉梅什 2 85 58   
塞卡 3 65 55   
悉达多 4 95 85    
拉吉 1 52 75   
塞卡 3 97 95   
悉达多 5 78 85   

我需要如下输出

名称 ID Sub1 Sub2
拉吉 1 127 151  
拉梅什 2 85 58   
塞卡 3 162 150    
悉达多 4 95 85  
悉达多 5 78 85   

也就是说,我需要将主题列中的标记总和并按 Id 列分组。我需要显示名称,但不应将其包含在 GroupBy 子句中。我应该如何编写查询以获得所需的结果?提前致谢。

4

3 回答 3

3

尝试这个 :-

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

或者你也使用SumandOver子句Subquery

 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演示

于 2013-03-24T11:54:20.097 回答
0

在所有的澄清之后,它似乎真的很简单:

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

SQL Fiddle 与演示

于 2013-03-24T11:38:41.113 回答
0

如果您需要Name从 group by 子句中排除,假设您的 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
于 2015-11-06T06:06:49.920 回答