Skip to content

Commit 06c1f11

Browse files
committed
some more window functions
1 parent a312c65 commit 06c1f11

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

src/main/java/dev/mayankg/db_concepts/mysql/exc06/window_funcs.sql

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,42 @@ SELECT
111111

112112
FROM employees
113113
ORDER BY overall_rank;
114+
115+
-- ASSIGN EACH EMPLOYEE TO A SALARY QUARTILE (Q1–Q4)
116+
-- Uses NTILE(4) to divide employees into 4 equal salary-based buckets
117+
-- Computes quartiles both department-wise and across the entire organization
118+
SELECT
119+
emp_no,
120+
department,
121+
salary,
122+
NTILE(4) OVER(PARTITION BY department ORDER BY salary DESC) AS dept_salary_quartile,
123+
NTILE(4) OVER(ORDER BY salary DESC) AS salary_quartile
124+
FROM employees;
125+
126+
-- IDENTIFY THE HIGHEST-PAID EMPLOYEE PER DEPARTMENT AND OVERALL
127+
-- FIRST_VALUE returns the emp_no with the highest salary per partition
128+
SELECT
129+
emp_no,
130+
department,
131+
salary,
132+
FIRST_VALUE(emp_no) OVER(PARTITION BY department ORDER BY salary DESC) AS highest_paid_dept,
133+
FIRST_VALUE(emp_no) OVER(ORDER BY salary DESC) AS highest_paid_overall
134+
FROM employees;
135+
136+
-- CALCULATE SALARY DIFFERENCE COMPARED TO THE PREVIOUS EMPLOYEE IN DESCENDING SALARY ORDER (OVERALL)
137+
-- LAG() fetches the previous row’s salary for comparison
138+
SELECT
139+
emp_no,
140+
department,
141+
salary,
142+
salary - LAG(salary) OVER(ORDER BY salary DESC) AS salary_diff
143+
FROM employees;
144+
145+
-- CALCULATE SALARY DIFFERENCE WITHIN EACH DEPARTMENT COMPARED TO THE NEXT LOWER PAID EMPLOYEE
146+
-- Uses LAG() within department partition to show gaps between adjacent salaries
147+
SELECT
148+
emp_no,
149+
department,
150+
salary,
151+
salary - LAG(salary) OVER(PARTITION BY department ORDER BY salary DESC) AS dept_salary_diff
152+
FROM employees;

0 commit comments

Comments
 (0)