关于SQL中的sum函数用法

辰爸 2009-04-11 10:16:02
数据库的表中有5条相似的记录,我想求前三条,应该怎么实现呢?
...全文
695 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
ws_hgo 2009-04-11
  • 打赏
  • 举报
回复
修改下

select sum(col) '总和' from
(
select top 3 * from #tb
) T
ws_hgo 2009-04-11
  • 打赏
  • 举报
回复

create table #TB(id int, col int)
insert #TB
select 1, 100 union all
select 2, 100 union all
select 3, 100 union all
select 4, 100 union all
select 5, 100

select id,sum(col) from
(
select top 3 * from #tb
) T
group by id
htl258_Tony 2009-04-11
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 tianshikuqi8 的回复:]
求前三条记录字段的总和!不好意思,没说明白!
[/Quote]
楼主已经说明白了,理解也没错。
csdyyr 2009-04-11
  • 打赏
  • 举报
回复
declare @tb table(id int, col int)
insert @tb
select 1, 100 union all
select 2, 100 union all
select 3, 100 union all
select 4, 100 union all
select 5, 100

set rowcount 3

declare @total int
set @total=0
select @total=@total+col from @tb
select @total as total

set rowcount 0
/*
total
-----------
300
*/
辰爸 2009-04-11
  • 打赏
  • 举报
回复
求前三条记录字段的总和!不好意思,没说明白!
dj3688 2009-04-11
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 htl258 的回复:]
引用 2 楼 dj3688 的回复:
引用楼主 tianshikuqi8 的帖子:
数据库的表中有5条相似的记录,我想求前三条,应该怎么实现呢?


select top 3 * from table?

这个跟sum函数有啥关系?

跟“前三条”有密切的关系
[/Quote]

..
xiequan2 2009-04-11
  • 打赏
  • 举报
回复
select sum(score) from tb10 where score in (select top 3 score from tb10 order by score desc)
htl258_Tony 2009-04-11
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 dj3688 的回复:]
引用楼主 tianshikuqi8 的帖子:
数据库的表中有5条相似的记录,我想求前三条,应该怎么实现呢?


select top 3 * from table?

这个跟sum函数有啥关系?
[/Quote]
跟“前三条”有密切的关系
htl258_Tony 2009-04-11
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 dj3688 的回复:]
引用楼主 tianshikuqi8 的帖子:
数据库的表中有5条相似的记录,我想求前三条,应该怎么实现呢?


select top 3 * from table?

这个跟sum函数有啥关系?
[/Quote]
跟前三条有密切的关系
dj3688 2009-04-11
  • 打赏
  • 举报
回复
Sum
返回在某一集合上对数值表达式求得的和。

语法
Sum(«Set»[, «Numeric Expression»])

示例
如果 USA、CANADA 和 MEXICO 成员的值分别为 1000、2000 和 3000,则以下示例返回 6000:

Sum({USA, CANADA, MEXICO}, Sales.VALUE)

以下示例更加直观,并且同样有效:

Sum({USA, CANADA, MEXICO}, Sales)

htl258_Tony 2009-04-11
  • 打赏
  • 举报
回复
select top 3 sum(col) scol from tb order by col

如果还不符合要求,请给出测试数据,谢谢!
dj3688 2009-04-11
  • 打赏
  • 举报
回复
[Quote=引用楼主 tianshikuqi8 的帖子:]
数据库的表中有5条相似的记录,我想求前三条,应该怎么实现呢?
[/Quote]

select top 3 * from table?

这个跟sum函数有啥关系?
mugua604 2009-04-11
  • 打赏
  • 举报
回复

select sum(col) from (
select top3 col from tableName ) a

22,206

社区成员

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

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