读书人

Sql中怎么实现连续相同的数据只取第一

发布时间: 2012-04-11 17:42:33 作者: rapoo

Sql中如何实现连续相同的数据只取第一条
例如:
Key Name Flag
110010
210021
310030
410040
510051
610061
710070
810080
910090
1010101
1110111
1210121

希望的结果是
Key Name Flag
110010
310030
710070
谢谢


[解决办法]

SQL code
select * from tabname awhere not exists (select 1 from tabname bwhere b.key = a.key - 1and b.flag = 0)and a.flag = 0
[解决办法]
SQL code
create table tab(Keys int, name int, Flag int)insert into tabselect 1, 1001, 0 union allselect 2, 1002, 1 union allselect 3, 1003, 0 union allselect 4, 1004, 0 union allselect 5, 1005, 1 union allselect 6, 1006, 1 union allselect 7, 1007, 0 union allselect 8, 1008, 0 union allselect 9, 1009, 0 union allselect 10, 1010, 1 union allselect 11, 1011, 1 union allselect 12, 1012, 1with pl as(select Keys,name,Flag,keys-row_number() over(order by Keys) rnfrom tab where Flag=0)select * from tab where keys in(select min(Keys)from pl group by rn)Keys        name        Flag----------- ----------- -----------1           1001        03           1003        07           1007        0(3 row(s) affected) 

读书人网 >SQL Server

热点推荐