-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql_joins.sql
More file actions
102 lines (75 loc) · 2.02 KB
/
sql_joins.sql
File metadata and controls
102 lines (75 loc) · 2.02 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use Practice
select * from dbo.colors
insert into dbo.colors values (1,'red')
insert into dbo.colors values (5,'Black')
select * from dbo.sizes
insert into dbo.sizes values (1,'S')
Insert into dbo.sizes values (4,'XXL')
--- Joins
-- INNER
select * from dbo.colors c
INNER JOIN dbo.sizes s
on c.color_id = s.size_id
-- Left
select * from colors c
left join sizes s
on c.color_id = s.size_id
-- Right
select * from colors c
right join sizes s
on c.color_id = s.size_id
--Outer Join
select * from colors c
full outer join sizes s
on c.color_id = s.size_id
---- Calculate the MODE
create table mode
(
id int
);
insert into mode values (1),(2),(2),(3),(3),(4),(4),(5);
-- Method 1 - CTE
with cte_freq as
(select id, count(*) as freq from mode group by id)
select * from cte_freq
where freq = (select max(freq) from cte_freq )
insert into mode values (4),(4),(4);
--Method 2 - Rank and two CTE's
with cte_freq_1 as
(select id, count(*) as freq from mode group by id)
, rk_cte as(
select id, freq, RANK() over( order by freq desc) as rk
from cte_freq_1)
select * from rk_cte where rk=1
----- Employees whos status is changed
create table emp_2020
(
emp_id int,
designation varchar(20)
);
create table emp_2021
(
emp_id int,
designation varchar(20)
)
insert into emp_2020 values (1,'Trainee'), (2,'Developer'),(3,'Senior Developer'),(4,'Manager');
insert into emp_2021 values (1,'Developer'), (2,'Developer'),(3,'Manager'),(5,'Trainee');
-- Solution
select isnull(e0.emp_id, e1.emp_id),
CASE when e0.designation != e1.designation then 'Promoted'
when e0.designation is null then 'New'
else 'Resigned'
End as comment
from emp_2020 e0
full outer join emp_2021 e1
on e0.emp_id = e1.emp_id
where isnull(e0.designation,'ABC') != isnull(e1.designation,'DEF')
-- create a duplicate based on column
with cte_freq as
(select id from mode group by id having count(*) > 1)
, rk_cte as
(select id, RANK() over(order by id) as rk from cte_freq)
select c.id, 'DUP ' + CAST(rc.rk as varchar(4)) rk_char
from rk_cte rc
right join mode c
on rc.id = c.id