@@ -138,24 +138,61 @@ JOIN sales2 sa ON c.car_id = sa.car_id
138
138
JOIN salespersons s ON sa .salesman_id = s .salesman_id
139
139
WHERE YEAR(sa .purchase_date ) = 2021 AND s .name = ' Emily Wong' ;
140
140
```
141
- car_id, make, type, style, cost_ $
142
- 2, Toyota, Corolla, Hatchback, 25000
143
- 4, Chevrolet, Camaro, Coupe, 36000```
144
-
145
141
146
142
### 7. What is the total revenue generated by the sales of hatchback cars?
147
143
148
- ``` SQL code ```
144
+ ``` SQL
145
+ SELECT SUM (c .cost_ $) AS Total_Revenue_Generated
146
+ FROM cars c
147
+ JOIN sales2 sa ON c .car_id = sa .car_id
148
+ WHERE c .style = ' Hatchback' ;
149
+ ```
149
150
### 8. What is the total revenue generated by the sales of SUV cars in the year 2022?
150
151
151
- ``` SQL code ```
152
+ ``` SQL
153
+ SELECT SUM (c .cost_ $) AS Total_Revenue_Generated
154
+ FROM cars c
155
+ JOIN sales2 sa ON c .car_id = sa .car_id
156
+ WHERE c .style = ' SUV' AND YEAR(sa .purchase_date ) = 2022 ;
157
+ select * from sales2;
158
+ select * from cars;
159
+ ```
152
160
153
161
### 9. What is the name and city of the salesperson who sold the most number of cars in the year 2023?
154
162
155
- ``` SQL code ```
163
+ ``` SQL
164
+ SELECT s .name AS Salesperson,
165
+ s .city
166
+ FROM salespersons s
167
+ JOIN (
168
+ -- Subquery calculates the rank of each salesperson based on the number of cars sold in 2023
169
+ SELECT salesman_id,
170
+ RANK() OVER (ORDER BY COUNT (* ) DESC ) AS Rnk
171
+ FROM sales2
172
+ WHERE YEAR(purchase_date) = 2023
173
+ GROUP BY salesman_id
174
+ ) t ON s .salesman_id = t .salesman_id
175
+ -- Select the top ranked result (salesperson with most cars sold)
176
+ WHERE Rnk = 1 ;
177
+ ```
156
178
157
179
### 10. What is the name and age of the salesperson who generated the highest revenue in the year 2022?
158
180
159
- ``` SQL code ```
181
+ ``` SQL
182
+ SELECT name AS Salesperson, age
183
+ FROM (
184
+ -- Subquery calculates total revenue generated by each salesperson in 2022 and assigns a rank
185
+ SELECT s .name ,
186
+ s .age ,
187
+ RANK() OVER (ORDER BY SUM (c .cost_ $) DESC ) AS rnk2
188
+ FROM salespersons s
189
+ JOIN sales2 ON s .salesman_id = sales2 .salesman_id
190
+ JOIN cars c ON sales2 .car_id = c .car_id
191
+ WHERE YEAR(purchase_date) = 2022
192
+ GROUP BY s .name , s .age
193
+ ) t
194
+ -- Select the top ranked result (salesperson with highest revenue)
195
+ WHERE rnk2 = 1 ;
196
+ ```
160
197
161
198
0 commit comments