日期:2014-05-18  浏览次数:20741 次

Sql中如何实现连续相同的数据只取第一条
例如:
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
谢谢


------解决方案--------------------
SQL code
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

------解决方案--------------------
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, 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)