求合并相邻记录的语句
时间:2011-11-17
来源:互联网
表记录如下:
NAME QUANTITY
----------------------------
a 1
a 1
b 2
b 2
a 1
a 1
b 2
b 2
要求相邻记录name相同的字段合并数量,结果如下:
NAME QUANTITY
----------------------------
a 2
b 4
a 2
b 4
sql语句如何写?
NAME QUANTITY
----------------------------
a 1
a 1
b 2
b 2
a 1
a 1
b 2
b 2
要求相邻记录name相同的字段合并数量,结果如下:
NAME QUANTITY
----------------------------
a 2
b 4
a 2
b 4
sql语句如何写?
作者: ShyZh 发布时间: 2011-11-17
SQL code
if object_id('[tb]') is not null drop table [tb] go create table [tb]([NAME] varchar(1),[QUANTITY] int) insert [tb] select 'a',1 union all select 'a',1 union all select 'b',2 union all select 'b',2 union all select 'a',1 union all select 'a',1 union all select 'b',2 union all select 'b',2 ;with t1 as (select rn=row_number() over(order by getdate()),* from [tb]), t2 as (select rn-(select count(1) from t1 where name=t.name and rn<=t.rn) gid,* from t1 t) SELECT NAME,SUM(QUANTITY) AS QUANTITY FROM T2 GROUP BY NAME,GID ORDER BY MIN(RN) /** NAME QUANTITY ---- ----------- a 2 b 4 a 2 b 4 (4 行受影响) **/
作者: josy 发布时间: 2011-11-17
--tb为原来的表,tmp为加了序号的临时表
select id = identity(int,1,1) into tmp from tb
select name , sum(QUANTITY) QUANTITY from tmp group by name , (px-1) / 2
select id = identity(int,1,1) into tmp from tb
select name , sum(QUANTITY) QUANTITY from tmp group by name , (px-1) / 2
作者: dawugui 发布时间: 2011-11-17
--tb为原来的表,tmp为加了序号的临时表
select id = identity(int,1,1) into tmp from tb
select name , sum(QUANTITY) QUANTITY from tmp group by name , (id-1) / 2
select id = identity(int,1,1) into tmp from tb
select name , sum(QUANTITY) QUANTITY from tmp group by name , (id-1) / 2
作者: dawugui 发布时间: 2011-11-17
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28