一个表结构有个字段是数字型,根据这个字段先排序,然后判断当前记录的该字段减去下一条记录的该字段大于某数的记录。如:记录如下... 5 ...
... 9 ...
... 6 ...
... 13 ...
... 12 ...求之差大于2的结果集?
查询出来的结果应该是:
... 6 ...
... 9 ...有没有一条sql语句查出来的?
实在不好弄,存储过程也行啊
... 9 ...
... 6 ...
... 13 ...
... 12 ...求之差大于2的结果集?
查询出来的结果应该是:
... 6 ...
... 9 ...有没有一条sql语句查出来的?
实在不好弄,存储过程也行啊
-- Author :fredrickhu(小F,向高手学习)
-- Date :2010-02-05 21:23:36
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int)
insert [tb]
select 5 union all
select 9 union all
select 6 union all
select 13 union all
select 12
--------------开始查询--------------------------
select
a.id
from
(select id0=row_number()over(order by id),* from tb)a,
(select id0=row_number()over(order by id),* from tb)b
where
a.id0=b.id0-1
and
b.id-a.id>2
----------------结果----------------------------
/* id
-----------
6
9(2 行受影响)*/
go
create table [tb]([value] int)
insert [tb]
select 5 union all
select 9 union all
select 6 union all
select 13 union all
select 12
goselect id=identity(int,1,1),* into # from tb order by value
goselect value
from # t
where exists(select 1 from # where id=t.id+1 and value>t.value+2)
go/**
value
-----------
6
9(所影响的行数为 2 行)
**/
from (
select a.col,max(b.col)
from 一个表 a ,一个表 b
where a.col>b.col
group by a.col
)
order by 2 desc
思路:生成行号,利用错位相减
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int)
insert [tb]
select 5 union all
select 9 union all
select 6 union all
select 13 union all
select 12select a.id from
(
select *, row=row_number() over(order by id) from tb
) a
,
(
select *, row=row_number() over(order by id) from tb
) b
where a.id-b.id>2 and a.row=b.row+1
/*
id
-----------
9
12(2 行受影响)
*/
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int)
insert [tb]
select 5 union all
select 9 union all
select 6 union all
select 13 union all
select 12
/*
根据这个字段先排序,然后判断当前记录的该字段减去下一条记录的该字段大于某数的记录...
求之差大于2的结果集
*/
--select * from dbo.tb
select a.id from tb a
left join tb b
on b.id>a.id
group by a.id
having min(b.id)-a.id>2
order by a.idid
-----------
6
9
left join tb b
on b.id>a.id
group by a.id
having min(b.id)-a.id>2
order by a.id