请高手看看这个查询语句该如何写 高分求

billy36 2007-02-19 10:14:42
A B
1 0101
2 0
3 0201
4 0
5 0902
6 0
7 1101
8 0
9 1102

要取得某条记录,方法是:提供一个变量C,要求取得一条字段B值为0的记录而且该记录的上一条和下一条记录中字段B的值不能于所提供的变量C相似。

比如一个变量0101则取得的记录不能为2应为4或6或8
...全文
214 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaoku 2007-02-20
  • 打赏
  • 举报
回复
--drop table t
create table t
(
A int identity(1,1) not null ,
B varchar(10)
)
insert into t(B) select '0101'
union all select '0'
union all select '0201'
union all select '0'
union all select '0902'
union all select '0'
union all select '1101'
union all select '0'
union all select '1102'


如果 A 连续且唯一
表名为t
select * from t m
where b=0 and not exists (select 1 from t n where n.b ='0101' and (m.A =n.A +1 or m.A =n.A -1) )

A B
----------- ----------
4 0
6 0
8 0

(所影响的行数为 3 行)
xiaoku 2007-02-20
  • 打赏
  • 举报
回复
--drop table t
create table t
(
A int identity(1,1) not null ,
B varchar(10)
)
insert into t(B) select '0101'
union all select '0'
union all select '0201'
union all select '0'
union all select '0902'
union all select '0'
union all select '1101'
union all select '0'
union all select '1102'


如果 A 连续且唯一
表名为t
select * from t m
where b=0 and not exists (select 1 from t n where n.b ='0101' and (m.A =n.A +1 or m.A =n.A -1) )

A B
----------- ----------
4 0
6 0
8 0

(所影响的行数为 3 行)
中国风 2007-02-20
  • 打赏
  • 举报
回复
declare @ta table
(A int ,B varchar(10))
insert into @ta select 1,'0101'
union all select 2,'0'
union all select 3,'0201'
union all select 4,'0'
union all select 5,'0902'
union all select 6,'0'
union all select 7,'1101'
union all select 8,'0'
union all select 9,'1102'
--把'0101'换为变量就行了
select * from @ta a
where b=0 and
not exists(select 1 from @ta where b='0101' and a!<a.a)
and
a not in(select top 1 a from @ta b where a >(select a from @ta where b='0101'))


(9 行受影响)
A B
----------- ----------
4 0
6 0
8 0

(3 行受影响)

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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