SQLServer2012中LEAD函式簡單分析

2022-04-08 06:42:23 字數 1671 閱讀 8373

lead函式簡單點說,就是把下一行的某列資料提取到當前行來顯示,看示例更能解釋清楚,先看測試用指令碼

declare @testdata table(

id int identity(1,1),

department varchar(20),

lastname varchar(20),

rate float )

insert into @testdata(department,lastname,rate)

select 'document control','arifin',17.7885 union all

select 'document control','norred',16.8269 union all

select 'document control','kharatishvili',16.8269 union all

select 'information services','chai',10.25 union all

select 'information services','berge',10.25 union all

select 'information services','trenary',50.4808 union all

select 'information services','conroy',39.6635 union all

select 'information services','ajenstat',38.4615 union all

select 'information services','wilson',38.4615 union all

select 'information services','connelly',32.4519 union all

select 'information services','meyyappan',32.4519

select * from @testdata

以上是原始資料,下邊應用lead函式,看下怎麼把其它行的資料提取到當前行顯示的

可以看到,lead函式把id為2的那一行的lastname值提取到第一行顯示為新列nextuser,就這麼個功能

下邊這個是間隔兩行提取資料,就是把第三行的資料提取到當前行,其它行以次累推,看圖

這個函式一共接受三個引數,第乙個是表示式,以上示例都使用的字段,還可以是其它有效的表示式,第二個引數是offset,即間隔多少行取資料,第三個是預設的間隔,即當沒有指定offset時以此為準

舉個例子,以上述**為例

lead(lastname,2,0)

當沒有指定那個2的時候,則以間隔0行為準,當有指定那個2的時候則間隔2行取資料,所以,往往第三個引數可以不指定,效果是一樣的,如下圖

與lead函式相對應的還有乙個函式,lag,看下圖效果

如上圖所示,這個函式是從上行取資料,其它間隔引數的意義一樣,lead是從下行取資料,tag相反是上行取資料,寫到這裡我就再想,如果指定負數,是不是就可以合併為乙個函式了?試下想法:

報錯,offset引數不能為負,哥不作評論,,,the end

lead(),over():ansi sql 2008 standard:關鍵是要ansi的

sql server 2005以上也有分析函式的,如果是2000,必須有乙個參照列,類似id之類的,

要看具體表結構

解除安裝sql server 2012

好不容易裝上了sql server2012資料庫,可是卻不能連線本地的資料庫,後來發現缺少一些服務,於是決定重新安裝,但是解除安裝卻很麻煩,如果解除安裝不乾淨的話,重新安裝會出問題,所以下面就總結一些方法 在解除安裝sql server 2012後,大家都希望能夠將登錄檔資訊完全刪乾淨,下面就將教您...

SQL Server2012中的Throw語句

簡 介sql server2012實現了 類似c 丟擲異常的 throw 語句。相比較於 sqlserver2005 之前使用 error,和sqlserver2005 之後使用 raiserror 引發 異常都是乙個不小的 進步,下面來看一下 throw 的用法。raiserror 和throw ...

SQLServer 2012 高效分頁

sql code 功能 生成測試資料.create table test paging id int identity 1,1 not null primary key,testnumber int not null,testname varchar 20 not null,testdept var...