求sql语句

dingzheng1989 2011-03-14 08:46:47
id score
1 60
2 70
3 70
1 45
5 24
2 80
4 88
1 70

上面的表我想分别计算不同id的score的累加和,例如id为1有三个score,60、45、70,我想要60+45+70=175,SQL语句应该怎么写?最后结果应该跟下面一样:

id sum
1 175
2 150
3 70
4 88
5 24

如果要加上按sum降序排列,又该怎么写?

id sum
1 175
2 150
4 88
3 70

5 24


谢谢了
...全文
44 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
dingzheng1989 2011-03-14
  • 打赏
  • 举报
回复
谢谢了
叶子 2011-03-14
  • 打赏
  • 举报
回复

declare @table table (id int,score int)
insert into @table
select 1,60 union all
select 2,70 union all
select 3,70 union all
select 1,45 union all
select 5,24 union all
select 2,80 union all
select 4,88 union all
select 1,70

select id,sum(score) as sumscore
from @table group by id
order by sum(score) desc
/*
id sumscore
----------- -----------
1 175
2 150
4 88
3 70
5 24
*/
王向飞 2011-03-14
  • 打赏
  • 举报
回复
select * from (select id,sum(score) as score
from table
group by id) t
order by score desc
王向飞 2011-03-14
  • 打赏
  • 举报
回复
id,sum(score)
from table
group by id

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧