-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql-practice-file-2.sql
More file actions
88 lines (60 loc) · 1.33 KB
/
sql-practice-file-2.sql
File metadata and controls
88 lines (60 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
-- ROW_NUMBER() problems
-- 1. Highest salary of each department
SELECT *
from (
SELECT e.*,
row_number() OVER(
partition by department_name ORDER BY salary DESC
) AS row_num
from employees AS e
)
AS emp WHERE row_num = 1;
-- 2. Finding duplicate values
SELECT employee_name, COUNT(*) AS count_value
from employees
GROUP BY employee_name
HAVING COUNT(*) > 1;
-- 3. Finding duplicate rows
SELECT *
from (
SELECT e.*,
row_number() OVER(
partition by employee_name
) AS row_num
from employees AS e
) emp
WHERE row_num > 1;
-- 4. Delete duplicate records keeping only one
DELETE
from employees
WHERE employee_id IN(
SELECT employee_id
from (
SELECT e.*,
row_number() OVER(
partition by employee_name
) AS row_num
from employees e
) emp
WHERE row_num > 1
);
-- 5. Find recently joined employee in each department
SELECT *
from (
SELECT e.*,
row_number() OVER(
partition by department_name order by date_joined DESC
) AS row_num
from employees AS e
) AS emp
WHERE row_num = 1;
-- 6. Find top 3 highest paid employees in each department
SELECT *
from (
SELECT e.*,
row_number() OVER(
partition by department_name order by salary DESC
) AS row_num
from employees AS e
) AS emp
WHERE row_num <= 3;