Sql中如何实现连续相同的数据只取第一条

Alden 2012-01-19 03:45:37
例如:
Key Name Flag
1 1001 0
2 1002 1
3 1003 0
4 1004 0
5 1005 1
6 1006 1
7 1007 0
8 1008 0
9 1009 0
10 1010 1
11 1011 1
12 1012 1

希望的结果是
Key Name Flag
1 1001 0
3 1003 0
7 1007 0
谢谢
...全文
1179 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
苦苦的潜行者 2012-01-19
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 ap0405140 的回复:]
SQL code

create table tab
(Keys int, name int, Flag int)

insert into tab
select 1, 1001, 0 union all
select 2, 1002, 1 union all
select 3, 1003, 0 union all
select 4, 1004, 0 union all
select 5, 10……
[/Quote]

唐诗,方法真妙啊,如诗一般..
怪不得叫唐诗..
苦苦的潜行者 2012-01-19
  • 打赏
  • 举报
回复
...
就当我秀下限了
create table t1([key] int,name int,flag int)
insert t1
select 1, 1001, 0 union all
select 2, 1002, 1 union all
select 3, 1003, 0 union all
select 4, 1004, 0 union all
select 5, 1005, 1 union all
select 6, 1006, 1 union all
select 7, 1007, 0 union all
select 8, 1008, 0 union all
select 9, 1009, 0 union all
select 10, 1010, 1 union all
select 11, 1011, 1 union all
select 12, 1012, 1
go
;with cte(id,[key],name,flag)
as
(
select ROW_NUMBER()over(order by [key]),* from t1
where flag=0
)
select top 1 [key] ,name,flag from cte
union all
select b.[key],b.name,b.flag from cte a,cte b
where a.id=b.id-1 and a.[key]<>b.[key] -1
/*
(3 行受影响)
key name flag
--- ---- ---
1 1001 0
3 1003 0
7 1007 0
*/
go
drop table t1
Alden 2012-01-19
  • 打赏
  • 举报
回复
太棒了,二位兄弟
唐诗三百首 2012-01-19
  • 打赏
  • 举报
回复

create table tab
(Keys int, name int, Flag int)

insert into tab
select 1, 1001, 0 union all
select 2, 1002, 1 union all
select 3, 1003, 0 union all
select 4, 1004, 0 union all
select 5, 1005, 1 union all
select 6, 1006, 1 union all
select 7, 1007, 0 union all
select 8, 1008, 0 union all
select 9, 1009, 0 union all
select 10, 1010, 1 union all
select 11, 1011, 1 union all
select 12, 1012, 1


with pl as
(select Keys,name,Flag,
keys-row_number() over(order by Keys) rn
from tab where Flag=0
)
select *
from tab where keys in
(select min(Keys)
from pl group by rn)

Keys name Flag
----------- ----------- -----------
1 1001 0
3 1003 0
7 1007 0

(3 row(s) affected)
昵称被占用了 2012-01-19
  • 打赏
  • 举报
回复
select * 
from tabname a
where not exists (
select 1 from tabname b
where b.key = a.key - 1
and b.flag = 0
)
and a.flag = 0

22,302

社区成员

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

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