T-SQL實現資料結構中的冒泡演算法和快速排序

來源:互聯網
上載者:User

 交換排序的基本思想是:兩兩比較待排序記錄的關鍵字,發現兩個記錄的次序相反時即進行交換,直到沒有反序的記錄為止。

  應用交換排序基本思想的主要排序方法有:冒泡排序和快速排序。

 

  一、下面我們來認識一下此方法在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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.