SQL window clause
The different window functions
- Sum
- Avg
- Count
- Lead
- Lag
- Rank
- Dense_rank
- Row_number
- Ntile
Syntax
SUM,COUNT, AVG
Department |
Employee |
Salary |
Avg_Salary_By_Dept |
IT |
Anand |
5000 |
|
Sales |
Roy |
6000 |
|
IT |
John |
4500 |
|
IT |
Patrick |
7500 |
|
Sales |
Richard |
6000 |
|
HR |
Ganesh |
6500 |
|
HR |
Vidya |
7500 |
|
LEAD,LAG
Query example
Department |
Employee |
Salary |
Joining date |
IT |
Anand |
5000 |
1-jan-2023 |
Sales |
Roy |
6000 |
1-jan-2023 |
IT |
John |
4500 |
2-jan-2023 |
IT |
Patrick |
7500 |
10-jan-2023 |
Sales |
Richard |
6000 |
30-dec-2022 |
HR |
Ganesh |
6500 |
11-aug-2022 |
HR |
Vidya |
7500 |
12-sep-2022 |
RANK,DESNSE_RANK,ROW_NUMBER
Department |
Employee |
Salary |
Joining date |
IT |
Anand |
5000 |
1-jan-2023 |
Sales |
Roy |
6000 |
1-jan-2023 |
IT |
John |
4500 |
2-jan-2023 |
IT |
Patrick |
7500 |
10-jan-2023 |
Sales |
Richard |
6000 |
30-dec-2022 |
HR |
Ganesh |
6500 |
11-aug-2022 |
HR |
Vidya |
7500 |
12-sep-2022 |
Department |
Employee |
Salary |
Joining date |
RANK_JD |
IT |
Anand |
5000 |
1-jan-2023 |
4 |
Sales |
Roy |
6000 |
1-jan-2023 |
4 |
IT |
John |
4500 |
2-jan-2023 |
6 |
IT |
Patrick |
7500 |
10-jan-2023 |
7 |
Sales |
Richard |
6000 |
30-dec-2022 |
3 |
HR |
Ganesh |
6500 |
11-aug-2022 |
1 |
HR |
Vidya |
7500 |
12-sep-2022 |
2 |
Department |
Employee |
Salary |
Joining date |
RANK_JD |
IT |
Anand |
5000 |
1-jan-2023 |
4 |
Sales |
Roy |
6000 |
1-jan-2023 |
4 |
IT |
John |
4500 |
2-jan-2023 |
5 |
IT |
Patrick |
7500 |
10-jan-2023 |
6 |
Sales |
Richard |
6000 |
30-dec-2022 |
3 |
HR |
Ganesh |
6500 |
11-aug-2022 |
1 |
HR |
Vidya |
7500 |
12-sep-2022 |
2 |
So if you see that RANK uses the number of rows to assign the next rank but dense_rank just uses the next consecutive number to assign value.
Department |
Employee |
Salary |
Joining date |
RANK_JD |
IT |
Anand |
5000 |
1-jan-2023 |
4 |
Sales |
Roy |
6000 |
1-jan-2023 |
5 |
IT |
John |
4500 |
2-jan-2023 |
6 |
IT |
Patrick |
7500 |
10-jan-2023 |
7 |
Sales |
Richard |
6000 |
30-dec-2022 |
3 |
HR |
Ganesh |
6500 |
11-aug-2022 |
1 |
HR |
Vidya |
7500 |
12-sep-2022 |
2 |
No comments:
Post a Comment