-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSession_14_Window_Functions_Part_2.sql
More file actions
101 lines (78 loc) · 2.15 KB
/
Copy pathSession_14_Window_Functions_Part_2.sql
File metadata and controls
101 lines (78 loc) · 2.15 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
101
CREATE DATABASE Session_14;
USE Session_14;
-- Task 1. Row Number --
CREATE TABLE Orders (
order_id INT AUTO_INCREMENT,
user_id INT,
order_date DATE,
total_amount DECIMAL(10,2),
PRIMARY KEY (order_id)
);
INSERT INTO Orders (user_id,order_date,total_amount)
VALUES (101, '2023-07-01', 500),
(101, '2023-07-05', 700),
(102, '2023-07-02', 1200),
(102, '2023-07-06', 800),
(103, '2023-07-03', 1500),
(103, '2023-07-07', 600);
SELECT order_id,user_id,order_date,total_amount,
ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY order_date DESC) AS Ranking
FROM Orders;
-- Task 2. Rank --
CREATE TABLE Songs (
song_id INT AUTO_INCREMENT,
artist VARCHAR(100),
streams INT,
PRIMARY KEY (song_id)
);
INSERT INTO Songs (artist,streams)
VALUES ('Arijit Singh', 500000),
('Arijit Singh', 450000),
('Arijit Singh', 450000),
('Shreya Ghoshal', 600000),
('Shreya Ghoshal', 550000);
SELECT song_id,artist,streams,
RANK() OVER(PARTITION BY artist ORDER BY streams DESC) AS stream_rank
FROM Songs;
-- Task 3. Dense Ranking --
CREATE TABLE Movies (
movie_id INT AUTO_INCREMENT,
genre VARCHAR(50),
rating DECIMAL(3,1),
PRIMARY KEY (movie_id)
);
INSERT INTO Movies (genre,rating)
VALUES ('Action', 4.8),
('Action', 4.5),
('Action', 4.5),
('Drama', 4.9),
('Drama', 4.7);
SELECT genre,movie_id,rating,
DENSE_RANK() OVER(PARTITION BY genre ORDER BY rating DESC) AS rating_rank
FROM Movies;
-- Task 4. Row_Number and CTE --
CREATE TABLE Influencers (
influencer_id INT AUTO_INCREMENT,
platform VARCHAR(50),
followers INT,
PRIMARY KEY (influencer_id)
);
INSERT INTO Influencers (platform,followers)
VALUES ('Instagram', 1000000),
('Instagram', 950000),
('Instagram', 900000),
('Twitter', 870000),
('Instagram', 850000),
('YouTube', 1200000),
('Twitter', 1000000),
('YouTube', 1100000),
('YouTube', 1050000),
('YouTube', 950000);
WITH RankedInfluencers AS (
SELECT platform,influencer_id,followers,
ROW_NUMBER() OVER(PARTITION BY platform ORDER BY followers DESC) AS rank_platform_wise
FROM Influencers
)
SELECT influencer_id, platform, rank_platform_wise
FROM RankedInfluencers
WHERE rank_platform_wise <= 3;