Oracle year-on-year comparison, detailed explanation of period-over-period comparison functions (LAG and LEAD)

Source: Internet
Author: User

The Lag and Lead functions can retrieve the data of the first N rows and the value of the last N rows of the same field in a query. This operation can be achieved through table join for the same table, but LAG and LEAD are more efficient.
Copy codeThe Code is as follows:
Create table salaryByMonth
(
EmployeeNo varchar2 (20 ),
YearMonth varchar2 (6 ),
Salary number
);
Insert into SALARYBYMONTH (EMPLOYEENO, YEARMONTH, SALARY)
Values (1, '20140901', 200805 );
Insert into SALARYBYMONTH (EMPLOYEENO, YEARMONTH, SALARY)
Values (1, '20140901', 200802 );
Insert into SALARYBYMONTH (EMPLOYEENO, YEARMONTH, SALARY)
Values (1, '20140901', 200803 );
Insert into SALARYBYMONTH (EMPLOYEENO, YEARMONTH, SALARY)
Values (1, '20140901', 200804 );
Insert into SALARYBYMONTH (EMPLOYEENO, YEARMONTH, SALARY)
Values (1, '20140901', 200708 );
Commit;

SELECT EMPLOYEENO
, YEARMONTH
, SALARY
, MIN (SALARY) KEEP (DENSE_RANK first order by yearmonth) OVER (partition by employeeno) FIRST_SALARY -- base ratio analysis salary/first_salary
, LAG (SALARY, 1, 0) OVER (partition by employeeno order by yearmonth) AS PREV_SAL-- Period-over-period comparison with last month
, LAG (SALARY, 12, 0) OVER (partition by employeeno order by yearmonth) AS PREV_12_SAL-- Compare the year-on-year analysis 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.