Professional Documents
Culture Documents
Analytic Functions - Using LAG For SCD Type 2 ClearPeaks Blog
Analytic Functions - Using LAG For SCD Type 2 ClearPeaks Blog
« Previous post
In one of my previous blog articles called ´´Deduplication using Analytic Function´´, I explained a simple introduction of Oracle Analytic
Functions. In this article (addressed for SQL developers), I will focus on the LAG function which from my point of view, is one of the
most useful functions. Let’s see the use of this function in a common Data Warehouse scenario: Slowly Changing Dimension.
The LAG analytic function gives access to multiple rows within a table, without the need of a self-join. Basically, it returns the value of
an attribute of the previous row.
The LEAD function (retrieves the value of the following rows) is similar to the LAG, in case we change the DESC/ASC attribute after the
ORDER BY clause.
We consider having a table with the currency Euros-Dollars: a column with the rate and another column with the date since this rate is
effective.
To simplify the following sample, we will work with a typical “Slowly Changing Dimension type 2” table, that means to have 2 columns
for the date range: “Valid Date From” and “Valid Date To”.
www.clearpeaks.com/blog/data-warehousing/analytic-functions-using-lag-for-scd-type-2#more-2967 1/3
1/21/13 Analytic Functions: Using LAG for SCD type 2 « ClearPeaks Blog
We can also have the same result using LEAD function but instead of having the order in DESC we should set it as ASC.
It is true that whatever an analytic function does, it can be done by native SQL, with self-joins and sub-queries. But the same routine
done by analytic function is always faster, or at least as fast as, when compared to native SQL.
Conclusion
We have seen that by using a simple LAG function we can avoid writing a complex SQL query, as we can see in our Slowly Changing
Dimension example.
Sometimes it seems that the analytic functions are more difficult than the native SQL, but as soon as we are familiar with the syntax,
we will be able to have a clear and easier to read code.
3 1 0 4
Leave a Comment
Name (required)
Website
Facebook
Twitter
Linkdn
RSS Feed
Blog Categories
Academy (17)
Analytics (1)
Customer Success Stories (2)
Data Management (1)
Data Warehousing (8)
ETL (11)
Events (18)
Exalytics (1)
General (18)
Oracle BI EE (36)
Oracle BI EE 11g (26)
Reporting (3)
Webinars (11)
www.clearpeaks.com/blog/data-warehousing/analytic-functions-using-lag-for-scd-type-2#more-2967 3/3