在SQL Server中如何合并相邻的重复记录

Taocarrier 2005-08-12 05:05:20
请教高手们一个问题:

假设在运行完一个SQL语句后,得到如下一个结果集:

F1 F2
------------
1 A
2 B
3 B
4 C
5 C
6 C

我如何再运行一个SQL语句才能得到下面这样的一个结果集呢?

F1 F2
------------
1 A
2 B
3 C

(即把F2字段相邻的、重复的记录合并为一个记录,这里记录的次序须保持不变)


先谢过了。
...全文
219 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
vivianfdlpw 2005-08-12
  • 打赏
  • 举报
回复
declare @tb table(F1 int,F2 varchar(10))
insert @tb
select 1,'A' union
select 2,'B' union
select 3,'B' union
select 4,'C' union
select 5,'C' union
select 6,'C'


select [F1]=(select count(1) from (select distinct F2 from @tb)A where F2<=t.F2),
F2
from @tb t
where not exists(select 1 from @tb where F2=t.F2 and F1>t.F1)

--结果
/*

F1 F2
----------- ----------
1 A
2 B
3 C

(所影响的行数为 3 行)
*/
vivianfdlpw 2005-08-12
  • 打赏
  • 举报
回复
declare @tb table(F1 int,F2 varchar(10))
insert @tb
select 1,'A' union
select 2,'B' union
select 3,'B' union
select 4,'C' union
select 5,'C' union
select 6,'C'


select [F1]=(select count(1) from (select distinct F2 from @tb)A where F2<=t.F2),
F2
from @tb t
where not exists(select 1 from @tb where F2=t.F2 and F1>t.F1)

--结果
/*

F1 F2
----------- ----------
1 A
2 B
3 C

(所影响的行数为 3 行)
*/
子陌红尘 2005-08-12
  • 打赏
  • 举报
回复
--生成测试数据
create table #T(F1 int,F2 char(1))
insert into #T select 1,'A'
insert into #T select 2,'B'
insert into #T select 3,'B'
insert into #T select 4,'C'
insert into #T select 5,'C'
insert into #T select 6,'C'


--执行查询语句
select
a.*
from
#T a
where
not exists(select 1 from #T where F1=a.F1-1 and F2=a.F2)


--输出查询结果
F1 F2
--- ---
1 A
2 B
4 C
520zyb 2005-08-12
  • 打赏
  • 举报
回复
select count(*),F2 from tb group by F2 order by F2

22,300

社区成员

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

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