循环写数据

shui1212 2007-12-05 02:57:38
读取表A的B项(int)记录,以4条数据为单位,求和之后写入表B中,求代码?
例:
表A
B
1
5
-3
2
5
3
-2
-8
写入表B后为
5
-2
...全文
107 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
火星求索 2007-12-05
  • 打赏
  • 举报
回复
按最后一组个数计算和
kk19840210 2007-12-05
  • 打赏
  • 举报
回复

create table #a (b int)
insert into #a values(1)
insert into #a values(5)
insert into #a values(-3)
insert into #a values(2)
insert into #a values(5)
insert into #a values(3)
insert into #a values(-2)
insert into #a values(-8)

create table #b(b int)

select id=identity(int,0,1) ,b into # from #a

insert into #b
select b=sum(b) from # group by id/4

select * from #b


b
-----------
5
-2

(2 行受影响)

kelph 2007-12-05
  • 打赏
  • 举报
回复
select identity(int,1,0) as id ,b into # from table


insert into b
select sum(b)
from #
group by id/4


drop table #
-狙击手- 2007-12-05
  • 打赏
  • 举报
回复
不好意思 ,我把函数参数搞错
select identity(int,0,1) as id ,b into # from tabe
kelph 2007-12-05
  • 打赏
  • 举报
回复
如果最后一组不够四条了怎么处理,剩下的算一组吗?
chuifengde 2007-12-05
  • 打赏
  • 举报
回复
declare @a table(a int)
insert @a select 1
union all select 5
union all select -3
union all select 2
union all select 5
union all select 3
union all select -2
union all select -8

declare @b table(id int identity(0,1),a int)
insert @b select * from @a

select sum(a) from @b group by id/4
--result
/*
-----------
5
-2

(所影响的行数为 2 行)*/
dawugui 2007-12-05
  • 打赏
  • 举报
回复
create table A(B int)
insert into A values(1)
insert into A values(5)
insert into A values(-3)
insert into A values(2)
insert into A values(5)
insert into A values(3)
insert into A values(-2)
insert into A values(-8)
create table B(B int)
go

select B , id = identity(int,0,1) into tmp from A

insert into B select 结果 from (select id = id/4 , 结果 = sum(B) from tmp group by id/4) t

select * from B

drop table A,B,tmp

/*
B
-----------
5
-2

(所影响的行数为 2 行)
*/
dawugui 2007-12-05
  • 打赏
  • 举报
回复
create table A(B int)
insert into A values(1)
insert into A values(5)
insert into A values(-3)
insert into A values(2)
insert into A values(5)
insert into A values(3)
insert into A values(-2)
insert into A values(-8)
go
select B , id = identity(int,0,1) into tmp from A

select id/4 , 结果 = sum(B) from tmp group by id/4

drop table A,tmp

/*
结果
----------- -----------
0 5
1 -2

(所影响的行数为 2 行)

*/
-狙击手- 2007-12-05
  • 打赏
  • 举报
回复
select identity(int,1,0) as id ,b into # from tabe


insert into b
select id,sum(b)
from #
group by id

drop table #

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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