oracle lag與lead分析函數簡介____靜態函數

來源:互聯網
上載者:User

原文連結點擊此處


lag與lead函數是跟位移量相關的兩個分析函數,通過這兩個函數我們可以取到當前行列的位移N行列的值 lag可以看著是正的向上的位移 lead可以認為負的向下的位移 具體我們來看幾個例子: 我們先看下scott的emp表的兩列資料: select deptno, sal from scott.emp order by deptno DEPTNO SAL 10 2450.00 10 5000.00 10 1300.00 20 2975.00 20 3000.00 20 1100.00 20 800.00 20 3000.00 30 1250.00 30 1500.00 30 1600.00 30 950.00 30 2850.00 30 1250.00 ok那現在比方我有個這樣的需求(我們只看sal列)我想問你2450的上一個值是多少。回答是沒有 那5000的上一個值是多少。是:2450 1300的上一個值是多少呢。是:5000 Ok以此類推我想得到當前值的上一個值 就像:2450      xxx(xxx代表空)--這個值是前一列的上一個值       5000.00 2450       1300.00 5000       2975.00 1300       3000.00 2975       1100.00 3000       ...       ...       1250.00   2850 OK就這樣的需求 那我們現在用SQL應該如何寫呢。是的你猜對了就是用lag分析函數: select deptno, sal a, lag(sal, 1, sal) b over(order by deptno)   from scott.emp DEPTNO A B 10 2450.00 2450 --ps:這裡的之所以是2450是因為lag(sal, 1, sal)我讓它給了他本身的值 10 5000.00 2450 10 1300.00 5000 20 2975.00 1300 20 3000.00 2975 20 1100.00 3000 20 800.00 1100 20 3000.00 800 30 1250.00 3000 30 1500.00 1250 30 1600.00 1500 30 950.00 1600 30 2850.00 950 30 1250.00 2850 是的就這麼簡單你看出A列與B列之間有何聯絡了吧 相對A列B列是她的上一個值 關於lead她就剛好與lag相反了 select deptno, sal a, lead(sal, 1, sal) over(order by deptno) b   from scott.emp DEPTNO A B 10 2450.00 5000 10 5000.00 1300 10 1300.00 2975 20 2975.00 3000 20 3000.00 1100 20 1100.00 800 20 800.00 3000 20 3000.00 1250 30 1250.00 1500 30 1500.00 1600 30 1600.00 950 30 950.00 2850 30 2850.00 1250 30 1250.00 1250 相對A列B列是她的下一個值 另外那個位移值1是可以隨便取的如果是2那就是位移兩個值了 select deptno, sal a, lag(sal, 2,null) over(order by deptno) b   from scott.emp DEPTNO A B 10 2450.00      --注意這裡是null空了 10 5000.00 10 1300.00 2450  --A列1300的上兩個值是多少。2450是吧 20 2975.00 5000 20 3000.00 1300 20 1100.00 2975 20 800.00 3000 20 3000.00 1100 30 1250.00 800 30 1500.00 3000 30 1600.00 1250 30 950.00 1500 30 2850.00 1600 30 1250.00 950 OK 那其實lag,lead還可以加上分組位移的 select deptno,        sal a,        lag(sal, 1, null) over( partition by deptno order by deptno) b   from scott.emp DEPTNO A B 10 2450.00 10 5000.00 2450 10 1300.00 5000 20 2975.00 20 3000.00 2975 20 1100.00 3000 20 800.00 1100 20 3000.00 800 30 1250.00 30 1500.00 1250 30 1600.00 1500 30 950.00 1600 30 2850.00 950 30 1250.00 2850 注意deptno不同的分組間的臨界值你看明白了吧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.