How to Use Windows Functions in SQL to Analyze Data Like a Pro(10)

 

What are Windows Functions?

How to Use Windows Functions?

function_name(arguments) OVER (
PARTITION BY partition_columns
ORDER
SELECT customer_id, order_id, order_date, amount,
SUM(amount) OVER (PARTITION BY customer_id) AS total_amount,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) AS order_number
FROM orders;

Examples of Windows Functions:

1)Row_Number():

SELECT employee_id, name, department, salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank
FROM employees;

2)Rank():

SELECT employee_id, name, department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank
FROM employees;

3)Dense_Rank():

SELECT employee_id, name, department, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank
FROM employees;

4)NTILE():

SELECT employee_id, name, department, salary,
NTILE(4) OVER (PARTITION BY department ORDER BY salary DESC) AS salary_quartile
FROM employees;

Conclusion:

Comments

Popular posts from this blog

Top 3 AI Tools for Programmers: Free Coding Assistants You Can’t Miss!

SQL Basics: A Guide for Students and Beginners(2)

MySQL for Beginners: Understanding Common Table Expressions (CTEs).(Part-13)