這個是乙個csdn上有人問的乙個題目,具體的題目如下:
資料庫表 表1
id name
1 db-235-aa-fc
2 db-275-ag-fw
3 db-235-ajj-fj
4 db-4444444-ss-fq
5 db-2222-kkk-fh
6 db-997-ii-fw
. .
. .
裡面幾千,幾萬條
在資料庫中寫查詢語句,查詢name欄位,第乙個『-』和第二個『-』之間的最大的那個數!
也就是把第4條資料查詢出來!
這裡給出了兩種解法:(1)是利用游標(在利用游標之前,會先過濾一下資料集,讓資料集的記錄變小,這樣可以大大的縮小游標所花的時間)具體的sql**如下:
create table #t
(id int not null identity(1,1) primary key,
name varchar(100) not null
)insert #t(name)
values
('db-235-aa-fc'),
('db-275-ag-fw'),
('db-235-ajj-fj'),
('db-4444444-ss-fq'),
('db-2222-kkk-fh'),
('db-997-ii-fw')
--下面的select就是縮小了結果集
select *
into #lists
from #t
where len(substring(name,1,charindex('-',name,4)-1))
in(select max(len(substring(name,1,charindex('-',name,4)-1))) from #t)
declare @name varchar(100)
declare @id int
declare @max int
set @max=-1
declare c cursor for
select * from #lists
open c
fetch next from c into @id,@name
while @@fetch_status=0
begin
set @name=substring(@name,1,charindex('-',@name,4)-1)
set @name=substring(@name,4,len(@name)-3)
if(cast(@name as int)>@max)
begin
set @max=cast(@name as int)
set @id=@id
endfetch next from c into @id,@name
endclose c
deallocate c
select * from #lists
where id=@id
drop table #lists
drop table #t
方法2:直接的操作,利用max(int),sql**如下:
create table #t
(id int not null identity(1,1) primary key,
name varchar(100) not null
)insert #t(name)
values
('db-235-aa-fc'),
('db-275-ag-fw'),
('db-235-ajj-fj'),
('db-4444444-ss-fq'),
('db-2222-kkk-fh'),
('db-997-ii-fw')
select * from #t
where substring(substring(name,1,charindex('-',name,4)-1),4,len(substring(name,1,charindex('-',name,4)-1))-3)
in(select max(cast(substring(substring(name,1,charindex('-',name,4)-1),4,len(substring(name,1,charindex('-',name,4)-1))-3) as int))
from #t
)drop table #t
結果都是相同的:4 db-4444444-ss-fq
oracle查詢某乙個欄位的數量總和
select count from select count from 表名稱 group by 多種資料量 表名 舉個栗子 比如說我有乙個資料型別的字段,裡面有很多種的資料型別。而且每個資料型別都有近些年的資料。就是有很多重複的資料型別的資料。我的目的就是查詢出 資料型別的個數。先查詢出不重複的資...
MySQL批量去掉某乙個字段特定的值
mysql批量去掉某乙個字段特定的值 比如,在表test中,欄位notice中,每一行記錄不知道為什麼都加了,訊息 現在要去除 訊息 字元。因為前面的字元一樣,所以可以批量把前兩個字母去掉就可以了。update test set notice replace notice,訊息 where noti...
DataTable中根據某乙個欄位來改變本行格式
效果如圖 根據紅色 字型這一列的資料,是到期日期,如果在乙個月內到期的話,那麼該行將會變成黃色顯示,並且到期日期將會變成紅色。關於columns 和 columndefs的區別,請看這篇 如下 aocolumndefs return data else return data 另外 createdc...