我有一张表说MyTable有两列Id
,Data
并且其中包含以下记录:
Id Data
----------
1. ABCDE00
2. DEFGH11
3. CCCCC21
4. AAAAA00
5. BBBBB10
6. vvvvv00
7. xxxxx88
现在我希望所有记录以字符串00
结尾并且没有后续行的列以11
结尾。
所以使用这个条件的输出应该是这样的:
1. AAAAA00
2. vvvvv00
任何帮助将不胜感激。
答案 0 :(得分:4)
这个答案做了一些假设:
id
。id
的行。在这种情况下,lead()
可以满足您的需求:
select t.*
from (select t.*, lead(data order by id) as next_data
from t
) t
where data like '%00' and (next_data not like '%11' or next_data is null);
早期版本的SQL Server具有计算next_data
的其他方法。
答案 1 :(得分:1)
如果有人没有使用sql server 2012,那么他们试试这个
declare @t table(id int identity(1,1),col1 varchar(100))
insert into @t values
('ABCDE00')
,('DEFGH11')
,('CCCCC21')
,('AAAAA00')
,('BBBBB10')
,('vvvvv00')
,('xxxxx88')
;With CTE as
(
select *,case when CHARINDEX('00',reverse(col1))>0 then 1 end
End00 from @t
)
,CTE1 as
(
select a.id,a.col1 from cte A
where exists
(select id from cte b where a.id=b.id+1 and b.end00 is not null)
and CHARINDEX('11',reverse(a.col1))<=0
)
select a.id,a.col1 from cte A
where exists
(select id from cte1 b where a.id=b.id-1 )