我有乙個表
num
001
002
003
004
007
008
009
我想讓他們變成區間形式
a b
001 004
007 009
如何才能辦到,我需要的是一條sql語句
declare
@ttable
(num
varchar(10
)) insert
into
@tselect
'001
'insert
into
@tselect
'002
'insert
into
@tselect
'003
'insert
into
@tselect
'004
'insert
into
@tselect
'007
'insert
into
@tselect
'008
'insert
into
@tselect
'009
'--法一:鑽鑽libin_ftsafe
select
a.num as[
a],min
(b.num) as[
b]from
(select
*from
@tt
where
notexists
(select
1from
@twhere
num=
t.num-1
)) a,
(select
*from
@tt
where
notexists
(select
1from
@twhere
num=
t.num+1
)) b
where
a.num
<=
b.num
group
bya.num
/*a b
---------- ----------
001 004
007 009*/
--法二:.net小鳥
declare
@ttable
(num
varchar(10
))insert
into
@tselect
'001
'union
allselect
'002
'union
allselect
'003
'union
allselect
'004
'union
allselect
'007
'union
allselect
'008
'union
allselect
'009'
declare
@ttable
(num
varchar(10
))insert
into
@tselect
'001
'union
allselect
'002
'union
allselect
'003
'union
allselect
'004
'union
allselect
'007
'union
allselect
'008
'union
allselect
'009
'select
min(num)
asa,
max(num)
asb
from
(select
px =
row_number()
over
(order
bynum),
*from
@t)t
group
bycast
(num
asint)-
px/*
001 004
007 009*/
--法三
:每天進步一點點
declare
@tbtable([
num]
varchar(3
))insert
@tbselect
'001
'union
allselect
'002
'union
allselect
'003
'union
allselect
'004
'union
allselect
'007
'union
allselect
'008
'union
allselect
'009';
with
cte as(
select
*,id
=row_number()
over
(order
bynum)
from
@tb)
,cte2 as(
select
top1
*,grp
=id
from
cte
whereid=
1union
allselectb.*
,case
when
b.num
=c.num+1
then
grp
else
grp+
1end
from
cte
asb,cte2
asc
where
b.id
=c.id+1
)select
min(num)
asa,
max(num) asb
from
cte2
group
bygrp
/*a b
---- ----
001 004
007 009*/
--法四: if
object_id('
[tb]')
isnot
null
drop
table[tb
]gocreate
table[tb
]([num
]varchar(10
))insert[tb
]select
'001
'union
allselect
'002
'union
allselect
'003
'union
allselect
'004
'union
allselect
'007
'union
allselect
'008
'union
allselect
'009'go
--增加輔助字段
alter
table
tb add
fid
intgo
--更新字段值
declare
@iint,@j
intupdate
tb set
fid=@i,
@i=case
when@j=
isnull
(cast
(num
asint),0
)-1then
isnull(@i
,0) else
isnull(@i
,0)+
1end,@j
=isnull
(cast
(num
asint),0
)go--查詢
selecta=
min(num),b
=max
(num)
from
tb group
byfid
--結果
/*a b
---------- ----------
001 004
007 009
(2 行受影響)
*/--
刪除輔助字段
alter
table
tb drop
column
fidgo
求一列數字的分割槽最大值與最小值
我有乙個表 num 001 002 003 004 007 008 009 我想讓他們變成區間形式 a b 001 004 007 009 如何才能辦到,我需要的是一條sql語句 declare ttable num varchar 10 insert into tselect 001 insert...
C PTA 求最大值最小值
用指標作函式引數,程式設計序求一維陣列中的最大和最小的元素值。函式介面定義 void maxmin int arr,int pt1,int pt2,int n 其中 arr pt1 pt2 n都是使用者傳入的引數,n為元素個數。函式求指標arr所指向的一維陣列中的最大和最小的元素值,並將最大值和最小...
求表中幾個列中最小值與最大值
今天有人問我這個問題,我只想到了greatest函式,沒有想到least函式,是查詢了 才知道的,說起來大家不太相信吧.sql desc t name null?type col1 number col2 number col3 number col4 number sql select from ...