SQL Analytic Functions

SQL’s analytic functions allow for complex calculations and deeper data insights

SQL’s analytic functions allow for complex calculations and in-depth analysis. They operate on rows in a query result set that are related to the current one.

I’ve prepared a thorough examination of common analytic functions for you.

These functions are intended to operate on a set of rows within a query result set that are related to the current row.

Understanding these functions will allow you to gain valuable insights into your data and make sound decisions.

Let’s use the table below as an example for the SQL command demonstration.

employee_iddepartmentemployee_namesalary
1HRAlice50000
2HRBob52000
3HRCarol48000
4ITDavid60000
5ITEmma65000
6FinanceFrank55000
7FinanceGrace58000

1. NTILE(n):

NTILE(n) divides the result set into roughly equal-sized groups or “tiles,” each with its own group number.  This function can be used to calculate quartiles or percentiles.

Examples

SQL
SQL
SQL
SELECT value, NTILE(4) OVER (ORDER BY value) AS quartile FROM dataset;

This query divides the dataset into four quartiles based on the value column

departmentemployee_namesalaryquartile
HRAlice500001
HRCarol480001
HRBob520002
ITDavid600003
ITEmma650004
FinanceFrank550003
FinanceGrace580004

2.PERCENTILE_CONT(value) WITHIN GROUP (ORDER BY column):

  • PERCENTILE_CONT calculates the value at a specified percentile within a group of rows. This is particularly helpful for finding the median or other specific percentiles.

Example

SQL
SQL
SQL
SELECT department, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary
FROM employees
GROUP BY department;

This query finds the median salary for each department.

departmentmedian_salary
HR50000
IT60000
Finance56500

3. PERCENTILE_DISC(value) WITHIN GROUP (ORDER BY column)

PERCENTILE DISC computes the value at a specified percentile within a group of rows, but instead of interpolated values, it returns an actual data value from the dataset.  It can be used to find discrete percentiles.

SQL
SQL
SQL
SELECT department, PERCENTILE_DISC(0.25) WITHIN GROUP (ORDER BY salary) AS first_quartile_salary
FROM employees
GROUP BY department;

This query finds the value at the first quartile (25th percentile) of salaries for each department.

departmentfirst_quartile_salary
HR49000
IT60000
Finance55000

4. CUME_DIST() WITHIN GROUP (ORDER BY column):

The cumulative distribution of a value within a group of rows is calculated by CUME DIST, indicating the relative position of a row within the group.

Example:

SQL
SQL
SQL
SELECT department, employee_name, salary, CUME_DIST() WITHIN GROUP (ORDER BY salary DESC) AS cumulative_salary_dist
FROM employees;

This query displays the cumulative distribution of salaries within the employees’ table, ordered by salary in descending order.

departmentemployee_namesalarycumulative_salary_dist
ITEmma650000.4285714286
FinanceGrace580000.8571428571
ITDavid600000.2857142857
FinanceFrank550000.5714285714
HRBob520001
HRAlice500000.8571428571
HRCarol480000.4285714286

5. Lag() and Lead():

The Lag() and Lead() functions allow you to access values from rows preceding or following a result set.  They are frequently used to calculate data shifts or patterns.

SQL
SQL
SQL
SELECT date, revenue, LAG(revenue) OVER (ORDER BY date) AS prev_day_revenue
FROM daily_sales;

This query retrieves the revenue for each day and the revenue for the previous day.

departmentemployee_namesalaryprev_employee_salarynext_employee_salary
HRAlice5000052000
HRBob520005000048000
HRCarol4800052000
ITDavid6000065000
ITEmma6500060000
FinanceFrank5500058000
FinanceGrace5800055000

6. First_Value() and Last_Value():

The functions First_Value() and Last_Value() return the first or last value within a group of rows in the specified order.

Example:

SQL
SQL
SQL
SELECT department, employee_name, salary,
       First_Value(employee_name) OVER (PARTITION BY department ORDER BY salary) AS lowest_paid_employee,
       Last_Value(employee_name) OVER (PARTITION BY department ORDER BY salary) AS highest_paid_employee
FROM employees;

This query finds the lowest- and highest-paid employees within each department.

departmentemployee_namesalarylowest_paid_employeehighest_paid_employee
HRAlice500004800052000
HRBob520004800052000
HRCarol480004800052000
ITDavid600006000065000
ITEmma650006000065000
FinanceFrank550005500058000
FinanceGrace580005500058000

Analytic functions are versatile data analysis and reporting tools that allow you to perform a wide range of calculations within specific groups or ordered sets of data.

These examples illustrate how common analytic functions operate on a dataset and provide valuable insights into data distribution, trends, and percentiles. Analytic functions are powerful tools for data analysis, reporting, and decision-making in SQL.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

  • ANCOVA: Analysis of Covariance with python

    ANCOVA is an extension of ANOVA (Analysis of Variance) that combines blocks of regression analysis and ANOVA. Which makes it Analysis of Covariance.

  • Learn Python The Fun Way

    What if we learn topics in a desirable way!! What if we learn to write Python codes from gamers data !!

  • Meet the most efficient and intelligent AI assistant : NotebookLM

    Start using NotebookLM today and embark on a smarter, more efficient learning journey!

  • Break the ice

    This can be a super guide for you to start and excel in your data science career.

  • Hypothesis Testing: A Comprehensive Overview

    This article delves into the application of hypothesis testing across diverse domains

  • Versions of ANCOVA (Analysis Of Covariance) with python

    To perform ANCOVA (Analysis of Covariance) with a dataset that includes multiple types of variables, you’ll need to ensure your dependent variable is continuous, and you can include categorical variables as factors. Below is an example using the statsmodels library in Python: Mock Dataset Let’s create a dataset with a mix of variable types: Performing…

  • Python Variables

    How useful was this post? Click on a star to rate it! Submit Rating Average rating 0 / 5. Vote count: 0 No votes so far! Be the first to rate this post.

  • A/B Testing Quiz

    Complete the code by dragging and dropping the correct functions

  • Python Functions

    Python functions are a vital concept in programming which enables you to group and define a collection of instructions. This makes your code more organized, modular, and easier to understand and maintain. Defining a Function: In Python, you can define a function via the def keyword, followed by the function name, any parameters wrapped in parentheses,…

  • Python Indexing: A Guide for Data Science Beginners

    Mastering indexing will significantly boost your data manipulation and analysis skills, a crucial step in your data science journey.

  • Diffusion Models: Making AI Creativity

    Stable Diffusion Models: Where Art and AI Collide Artificial Intelligence meets creativity in the fascinating realm of Stable Diffusion Models. These innovative models take text descriptions and bring them to life in the form of detailed and realistic images. Let’s embark on a journey to understand the magic behind Stable Diffusion in a way that’s…

  • Quiz Challenge: Basics with Python [Questions]

    Solve These Questions in Following Challange

  • Introducing Plethora of Stable Diffusion models: Part 1

    Generate AI images as good as DALL-E completely offline.

One response to “SQL Analytic Functions”

Points You Earned

Untitled design 6
0 distinction_points
Untitled design 5
python_points 0
0 Solver points
Instagram
WhatsApp
error: Content is protected !!