Oracle for the year, the chain function (lag and lead) of the detailed _oracle

Source: Internet
Author: User

The lag and lead functions can fetch the first n rows of data from the same field and the values of the latter n rows in a single query. This can be done using table joins to the same table, but with lag and leads is more efficient.

Copy Code code as follows:

CREATE TABLE Salarybymonth
(
Employeeno varchar2 (20),
Yearmonth VARCHAR2 (6),
Salary number
) ;
Insert into Salarybymonth (Employeeno, Yearmonth, SALARY)
VALUES (1, ' 200805 ', 500);
Insert into Salarybymonth (Employeeno, Yearmonth, SALARY)
VALUES (1, ' 200802 ', 150);
Insert into Salarybymonth (Employeeno, Yearmonth, SALARY)
VALUES (1, ' 200803 ', 200);
Insert into Salarybymonth (Employeeno, Yearmonth, SALARY)
VALUES (1, ' 200804 ', 300);
Insert into Salarybymonth (Employeeno, Yearmonth, SALARY)
VALUES (1, ' 200708 ', 100);
Commit

SELECT Employeeno
, Yearmonth
, SALARY
, MIN (SALARY) KEEP (Dense_rank A/Yearmonth) over (PARTITION by Employeeno) first_salary--Gibe analysis Salary/first_sal ary
, LAG (SALARY, 1, 0) over (PARTITION by Employeeno Order by Yearmonth) as Prev_sal --chain analysis, compared with last month
, LAG (SALARY, 0) over (PARTITION by Employeeno Order by Yearmonth) as Prev_12_sal --year-on-year analysis, compared with the same month of the previous year
, SUM (SALARY) over (PARTITION by Employeeno, SUBSTR (Yearmonth, 1, 4) Order by Yearmonth RANGE unbounded preceding) LJ--Cumulative value
From Salarybymonth
ORDER BY Employeeno
, Yearmonth


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.