T-SQL與數據結構的冒泡算法
來源:程序員人生 發布時間:2014-04-05 01:47:04 閱讀次數:2860次
交換排序的基本思想是:兩兩比較待排序記錄的關鍵字,發現兩個記錄的次序相反時即進行交換,直到沒有反序的記錄為止。應用交換排序基本思想的主要排序方法有:冒泡排序和快速排序。
一、下面我們來認識一下此方法在T-SQL中的實際使用:
declare @date datetime
declare @endDate datetime
declare @termID int
set @termID=46 --在此設置機器號
set @date='2008-8-8' --在此設置開始日期
set @endDate='2008-8-27' --在此設置結束日期
select t1.rownumber,t1.termid,t1.termrecordid,t2.rownumber,t2.termrecordid,t1.tcrdate, t2.termRecordid-t1.termRecordid as 差值
from(
select ROW_NUMBER() OVER (order by termid, termRecordID)as RowNumber,termid, termRecordID,tcrdate
from TE_TermCollectRecords
where tcrdate>=@date and tcrdate<@enddate
) t1,(
select ROW_NUMBER() OVER (order by termid,termRecordID)as RowNumber,termid, termRecordID,tcrdate
from TE_TermCollectRecords
where tcrdate>=@date and tcrdate<@enddate
) t2
where t2.rowNumber=t1.rowNumber+1 AND t2.termRecordid-t1.termRecordid>1
order by t1.tcrdate,t1.termid
1、其實上面首先是利用了子查詢,查詢出了兩個帶參數的完全一樣的表,利用了SQL2005中帶有的一個函數ROW_NUMBER()查詢出了相應的行號,使用第二個去跟第一個進行較,若之差大于1則表示此數據前后的兩條數據不連續有斷號現象,也就實現了我查找丟失流水的信息。
當然,我們在SQL2000中則可以利用Identity(int,1,1)這個函數來實現查詢每行流水。
2、由此想到了另外一些有關于子查詢的事情也利用這個行號來解決。遇到一個客戶的數據庫時間跳變太無規率的跳變,只能將大致的時間調整回來。其整個表結構有兩個字段Termrecordid和consumedate兩個欄位應該是一直遞增的,因為時間跳得已經完全沒有任何可尋解后,想直接利用現存的時候將時間按照Termrecordid進行一個一個的更新
具體操作法如下:
select *,identity(int,1,1) as rowindex into #tempp from econsumedata where
deviceid=6 and recordid>111 order by recordid ---將所有異常數據都查詢出來,且生成了一列以行號為值的列
go
select recordid,consumedate,rowindex from #tempp ---將兩個標志欄位查詢出來以及行號
go
update a
set a.consumedate=b.consumedate
from #tempp a inner join #temp1 b on a.rowindex=b.rowdex --利用行號作為聯接條件進行更新
go
update a
set a.consumedate=b.consumedate
from econsumedata a inner join #tempp b on a.recordid=b.recordid
where a.deviceid=6 and a.recordid>111 ---更新正式表
drop table #tempp
drop table #temp1
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈