├── README.md └── Solutions ├── Problem-27.sql ├── Problem-22.sql ├── Problem-02.sql ├── Problem-24.sql ├── Problem-29.sql ├── Problem-23.sql ├── Problem-35.sql ├── Problem-20.sql ├── Problem-05.sql ├── Problem-09.sql ├── Problem-15.sql ├── Problem-01.sql ├── Problem-37.sql ├── Problem-13.sql ├── Problem-04.sql ├── Problem-32.sql ├── Problem-30.sql ├── Problem-34.sql ├── Problem-03.sql ├── Problem-21.sql ├── Problem-31.sql ├── Problem-43.sql ├── Problem-19.sql ├── Problem-38.sql ├── Problem-28.sql ├── Problem-18.sql ├── Problem-06.sql ├── Problem-11.sql ├── Problem-25.sql ├── Problem-07.sql ├── Problem-08.sql ├── Problem-17.sql ├── Problem-33.sql ├── Problem-36.sql ├── Problem-42.sql ├── Problem-40.sql ├── Problem-26.sql ├── Problem-41.sql ├── Problem-39.sql ├── Problem-45.sql ├── Problem-16.sql ├── Problem-14.sql ├── Problem-44.sql ├── Problem-12.sql └── Problem-10.sql /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode-MySql 2 | 3 | ### Solution Of Leetcode-MySql Challenges. 👉👉[View Here](https://github.com/Shubham-Bhoite/LeetCode-MySql/tree/main/Solutions)👈👈 4 | -------------------------------------------------------------------------------- /Solutions/Problem-27.sql: -------------------------------------------------------------------------------- 1 | /* 27.Triangle Judgement : 2 | 3 | Table: Triangle 4 | +-------------+------+ 5 | | Column Name | Type | 6 | +-------------+------+ 7 | | x | int | 8 | | y | int | 9 | | z | int | 10 | +-------------+------+ 11 | In SQL, (x, y, z) is the primary key column for this table. 12 | Each row of this table contains the lengths of three line segments. 13 | 14 | Report for every three line segments whether they can form a triangle. 15 | */ 16 | 17 | SELECT x, y, z, 18 | CASE WHEN x + y > z AND x + z > y AND y + z > x THEN 'Yes' ELSE 'No' 19 | END AS triangle 20 | FROM Triangle; -------------------------------------------------------------------------------- /Solutions/Problem-22.sql: -------------------------------------------------------------------------------- 1 | /* 22.Classes More Than 5 Students : 2 | 3 | Table: Courses 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | student | varchar | 8 | | class | varchar | 9 | +-------------+---------+ 10 | (student, class) is the primary key (combination of columns with unique values) for this table. 11 | Each row of this table indicates the name of a student and the class in which they are enrolled. 12 | 13 | Write a solution to find all the classes that have at least five students. 14 | */ 15 | 16 | SELECT class 17 | FROM Courses 18 | GROUP BY class 19 | HAVING COUNT(student) >= 5; 20 | -------------------------------------------------------------------------------- /Solutions/Problem-02.sql: -------------------------------------------------------------------------------- 1 | /* 2.Find Customer Referee : 2 | 3 | Table: Customer 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | id | int | 8 | | name | varchar | 9 | | referee_id | int | 10 | +-------------+---------+ 11 | In SQL, id is the primary key column for this table. 12 | Each row of this table indicates the id of a customer, their name, and the id of the customer who referred them. 13 | 14 | Find the names of the customer that are not referred by the customer with id = 2. 15 | Return the result table in any order. 16 | */ 17 | 18 | select name from customer 19 | where ifnull (referee_id, 1)<>2; -------------------------------------------------------------------------------- /Solutions/Problem-24.sql: -------------------------------------------------------------------------------- 1 | /* 24.Biggest Single Number : 2 | 3 | Table: MyNumbers 4 | +-------------+------+ 5 | | Column Name | Type | 6 | +-------------+------+ 7 | | num | int | 8 | +-------------+------+ 9 | This table may contain duplicates (In other words, there is no primary key for this table in SQL). 10 | Each row of this table contains an integer. 11 | 12 | A single number is a number that appeared only once in the MyNumbers table. 13 | Find the largest single number. If there is no single number, report null. 14 | */ 15 | 16 | SELECT MAX(num) AS num 17 | FROM ( 18 | SELECT num 19 | FROM MyNumbers 20 | GROUP BY num 21 | HAVING COUNT(num) = 1) 22 | AS single_numbers; -------------------------------------------------------------------------------- /Solutions/Problem-29.sql: -------------------------------------------------------------------------------- 1 | /* 29.Fix Names in a Table : 2 | 3 | Table: Users 4 | +----------------+---------+ 5 | | Column Name | Type | 6 | +----------------+---------+ 7 | | user_id | int | 8 | | name | varchar | 9 | +----------------+---------+ 10 | user_id is the primary key (column with unique values) for this table. 11 | This table contains the ID and the name of the user. The name consists of only lowercase and uppercase characters. 12 | 13 | Write a solution to fix the names so that only the first character is uppercase and the rest are lowercase. 14 | */ 15 | 16 | SELECT user_id, CONCAT(UPPER(LEFT(name, 1)), LOWER(SUBSTRING(name, 2))) AS name 17 | FROM Users 18 | ORDER BY user_id; 19 | -------------------------------------------------------------------------------- /Solutions/Problem-23.sql: -------------------------------------------------------------------------------- 1 | /* 23.Find Followers Count : 2 | 3 | Table: Followers 4 | +-------------+------+ 5 | | Column Name | Type | 6 | +-------------+------+ 7 | | user_id | int | 8 | | follower_id | int | 9 | +-------------+------+ 10 | (user_id, follower_id) is the primary key (combination of columns with unique values) for this table. 11 | This table contains the IDs of a user and a follower in a social media app where the follower follows the user. 12 | 13 | Write a solution that will, for each user, return the number of followers. 14 | Return the result table ordered by user_id in ascending order. 15 | */ 16 | 17 | SELECT user_id, COUNT(follower_id) AS followers_count 18 | FROM Followers 19 | GROUP BY user_id 20 | ORDER BY user_id ASC; -------------------------------------------------------------------------------- /Solutions/Problem-35.sql: -------------------------------------------------------------------------------- 1 | /* 35.Second Highest Salary : 2 | 3 | Table: Employee 4 | +-------------+------+ 5 | | Column Name | Type | 6 | +-------------+------+ 7 | | id | int | 8 | | salary | int | 9 | +-------------+------+ 10 | id is the primary key (column with unique values) for this table. 11 | Each row of this table contains information about the salary of an employee. 12 | 13 | Write a solution to find the second highest distinct salary from the Employee table. If there is no second highest salary, return null (return None in Pandas). 14 | */ 15 | 16 | 17 | SELECT ( 18 | SELECT DISTINCT salary 19 | FROM Employee 20 | ORDER BY salary DESC 21 | LIMIT 1 OFFSET 1 22 | ) AS SecondHighestSalary; 23 | -------------------------------------------------------------------------------- /Solutions/Problem-20.sql: -------------------------------------------------------------------------------- 1 | /* 20. Number of Unique Subjects Taught by Each Teacher : 2 | 3 | Table: Teacher 4 | +-------------+------+ 5 | | Column Name | Type | 6 | +-------------+------+ 7 | | teacher_id | int | 8 | | subject_id | int | 9 | | dept_id | int | 10 | +-------------+------+ 11 | (subject_id, dept_id) is the primary key (combinations of columns with unique values) of this table. 12 | Each row in this table indicates that the teacher with teacher_id teaches the subject subject_id in the department dept_id. 13 | 14 | Write a solution to calculate the number of unique subjects each teacher teaches in the university. 15 | */ 16 | 17 | SELECT 18 | teacher_id, 19 | COUNT(DISTINCT subject_id) AS cnt 20 | FROM 21 | Teacher 22 | GROUP BY 23 | teacher_id; -------------------------------------------------------------------------------- /Solutions/Problem-05.sql: -------------------------------------------------------------------------------- 1 | /* 5.Invalid Tweets : 2 | 3 | Table: Tweets 4 | +----------------+---------+ 5 | | Column Name | Type | 6 | +----------------+---------+ 7 | | tweet_id | int | 8 | | content | varchar | 9 | +----------------+---------+ 10 | tweet_id is the primary key (column with unique values) for this table. 11 | content consists of characters on an American Keyboard, and no other special characters. 12 | This table contains all the tweets in a social media app. 13 | 14 | Write a solution to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15. 15 | Return the result table in any order. 16 | */ 17 | 18 | SELECT TWEET_ID 19 | FROM TWEETS 20 | WHERE LENGTH(CONTENT) > 15; -------------------------------------------------------------------------------- /Solutions/Problem-09.sql: -------------------------------------------------------------------------------- 1 | /* 9.Rising Temperature: 2 | 3 | Table: Weather 4 | +---------------+---------+ 5 | | Column Name | Type | 6 | +---------------+---------+ 7 | | id | int | 8 | | recordDate | date | 9 | | temperature | int | 10 | +---------------+---------+ 11 | id is the column with unique values for this table. 12 | There are no different rows with the same recordDate. 13 | This table contains information about the temperature on a certain day. 14 | 15 | Write a solution to find all dates' id with higher temperatures compared to its previous dates (yesterday). 16 | Return the result table in any order. 17 | */ 18 | 19 | select w2.id from Weather w1 join 20 | Weather w2 on 21 | date_sub(w2.recordDate, interval 1 day)= w1.recordDate 22 | and w2.temperature>w1.temperature; -------------------------------------------------------------------------------- /Solutions/Problem-15.sql: -------------------------------------------------------------------------------- 1 | /* 15.Not Boring Movies : 2 | 3 | Table: Cinema 4 | +----------------+----------+ 5 | | Column Name | Type | 6 | +----------------+----------+ 7 | | id | int | 8 | | movie | varchar | 9 | | description | varchar | 10 | | rating | float | 11 | +----------------+----------+ 12 | id is the primary key (column with unique values) for this table. 13 | Each row contains information about the name of a movie, its genre, and its rating. 14 | rating is a 2 decimal places float in the range [0, 10] 15 | 16 | Write a solution to report the movies with an odd-numbered ID and a description that is not "boring". 17 | Return the result table ordered by rating in descending order. 18 | */ 19 | 20 | SELECT * FROM Cinema 21 | WHERE id%2 !=0 AND Description !='boring' 22 | ORDER BY rating DESC -------------------------------------------------------------------------------- /Solutions/Problem-01.sql: -------------------------------------------------------------------------------- 1 | /* 1.Recyclable and Low Fat Products : 2 | 3 | Table: Products 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | product_id | int | 8 | | low_fats | enum | 9 | | recyclable | enum | 10 | +-------------+---------+ 11 | product_id is the primary key (column with unique values) for this table. 12 | low_fats is an ENUM (category) of type ('Y', 'N') where 'Y' means this product is low fat and 'N' means it is not. 13 | recyclable is an ENUM (category) of types ('Y', 'N') where 'Y' means this product is recyclable and 'N' means it is not. 14 | 15 | Write a solution to find the ids of products that are both low fat and recyclable. 16 | Return the result table in any order. 17 | */ 18 | 19 | 20 | select product_id 21 | from products 22 | where low_fats = "Y" and recyclable = "Y"; -------------------------------------------------------------------------------- /Solutions/Problem-37.sql: -------------------------------------------------------------------------------- 1 | /* 37.Exchange Seats : 2 | 3 | Table: Seat 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | id | int | 8 | | student | varchar | 9 | +-------------+---------+ 10 | id is the primary key (unique value) column for this table. 11 | Each row of this table indicates the name and the ID of a student. 12 | The ID sequence always starts from 1 and increments continuously. 13 | 14 | Write a solution to swap the seat id of every two consecutive students. If the number of students is odd, the id of the last student is not swapped. 15 | */ 16 | 17 | SELECT 18 | CASE 19 | WHEN MOD(id, 2) = 1 AND id + 1 <= (SELECT MAX(id) FROM Seat) THEN id + 1 20 | WHEN MOD(id, 2) = 0 THEN id - 1 21 | ELSE id 22 | END AS id, 23 | student 24 | FROM Seat 25 | ORDER BY id; 26 | -------------------------------------------------------------------------------- /Solutions/Problem-13.sql: -------------------------------------------------------------------------------- 1 | /* 13.Managers with at Least 5 Direct Reports : 2 | 3 | Table: Employee 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | id | int | 8 | | name | varchar | 9 | | department | varchar | 10 | | managerId | int | 11 | +-------------+---------+ 12 | id is the primary key (column with unique values) for this table. 13 | Each row of this table indicates the name of an employee, their department, and the id of their manager. 14 | If managerId is null, then the employee does not have a manager. 15 | No employee will be the manager of themself. 16 | 17 | Write a solution to find managers with at least five direct reports. 18 | */ 19 | 20 | SELECT e1.name 21 | FROM Employee e1 22 | INNER JOIN Employee e2 23 | ON e1.id=e2.managerId 24 | GROUP BY e2.managerId 25 | HAVING COUNT(e2.managerId) >= 5 -------------------------------------------------------------------------------- /Solutions/Problem-04.sql: -------------------------------------------------------------------------------- 1 | /* 4.Article Views I : 2 | 3 | Table: Views 4 | +---------------+---------+ 5 | | Column Name | Type | 6 | +---------------+---------+ 7 | | article_id | int | 8 | | author_id | int | 9 | | viewer_id | int | 10 | | view_date | date | 11 | +---------------+---------+ 12 | There is no primary key (column with unique values) for this table, the table may have duplicate rows. 13 | Each row of this table indicates that some viewer viewed an article (written by some author) on some date. 14 | Note that equal author_id and viewer_id indicate the same person. 15 | 16 | Write a solution to find all the authors that viewed at least one of their own articles. 17 | Return the result table sorted by id in ascending order. 18 | */ 19 | 20 | select distinct author_id id 21 | from views 22 | where author_id=viewer_id 23 | order by author_id; -------------------------------------------------------------------------------- /Solutions/Problem-32.sql: -------------------------------------------------------------------------------- 1 | /*32.Group Sold Products By The Date : 2 | 3 | Table Activities: 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | sell_date | date | 8 | | product | varchar | 9 | +-------------+---------+ 10 | There is no primary key (column with unique values) for this table. It may contain duplicates. 11 | Each row of this table contains the product name and the date it was sold in a market. 12 | 13 | Write a solution to find for each date the number of different products sold and their names. 14 | The sold products names for each date should be sorted lexicographically. 15 | */ 16 | 17 | 18 | SELECT sell_date, 19 | COUNT(DISTINCT product) AS num_sold, 20 | GROUP_CONCAT(DISTINCT product ORDER BY product SEPARATOR ',') AS products 21 | FROM Activities 22 | GROUP BY sell_date 23 | ORDER BY sell_date; 24 | -------------------------------------------------------------------------------- /Solutions/Problem-30.sql: -------------------------------------------------------------------------------- 1 | /* 30.Patients With a Condition : 2 | 3 | Table: Patients 4 | +--------------+---------+ 5 | | Column Name | Type | 6 | +--------------+---------+ 7 | | patient_id | int | 8 | | patient_name | varchar | 9 | | conditions | varchar | 10 | +--------------+---------+ 11 | patient_id is the primary key (column with unique values) for this table. 12 | 'conditions' contains 0 or more code separated by spaces. 13 | This table contains information of the patients in the hospital. 14 | 15 | Write a solution to find the patient_id, patient_name, and conditions of the patients who have Type I Diabetes. Type I Diabetes always starts with DIAB1 prefix. 16 | */ 17 | 18 | SELECT patient_id, patient_name, conditions 19 | FROM Patients 20 | WHERE conditions LIKE 'DIAB1%' 21 | OR conditions LIKE '% DIAB1%' 22 | OR conditions LIKE '% DIAB1 %' 23 | OR conditions = 'DIAB1'; 24 | -------------------------------------------------------------------------------- /Solutions/Problem-34.sql: -------------------------------------------------------------------------------- 1 | /*34.Find Users With Valid E-Mails : 2 | 3 | Table: Users 4 | +---------------+---------+ 5 | | Column Name | Type | 6 | +---------------+---------+ 7 | | user_id | int | 8 | | name | varchar | 9 | | mail | varchar | 10 | +---------------+---------+ 11 | user_id is the primary key (column with unique values) for this table. 12 | This table contains information of the users signed up in a website. Some e-mails are invalid. 13 | 14 | Write a solution to find the users who have valid emails. 15 | 16 | A valid e-mail has a prefix name and a domain where: 17 | The prefix name is a string that may contain letters (upper or lower case), digits, underscore '_', period '.', and/or dash '-'. The prefix name must start with a letter. 18 | The domain is '@leetcode.com'. 19 | */ 20 | 21 | SELECT * 22 | FROM Users 23 | WHERE mail REGEXP '^[a-zA-Z][a-zA-Z0-9._-]*@leetcode\\.com$'; 24 | -------------------------------------------------------------------------------- /Solutions/Problem-03.sql: -------------------------------------------------------------------------------- 1 | /* 3.Big Countries : 2 | 3 | Table: World 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | name | varchar | 8 | | continent | varchar | 9 | | area | int | 10 | | population | int | 11 | | gdp | bigint | 12 | +-------------+---------+ 13 | name is the primary key (column with unique values) for this table. 14 | Each row of this table gives information about the name of a country, the continent to which it belongs, its area, the population, and its GDP value. 15 | 16 | A country is big if: 17 | - it has an area of at least three million (i.e., 3000000 km2), or 18 | - it has a population of at least twenty-five million (i.e., 25000000). 19 | Write a solution to find the name, population, and area of the big countries. 20 | Return the result table in any order. 21 | */ 22 | 23 | select name, population, area 24 | from world 25 | where area >= 3000000 || population >= 25000000; -------------------------------------------------------------------------------- /Solutions/Problem-21.sql: -------------------------------------------------------------------------------- 1 | /* 21.User Activity for the Past 30 Days I: 2 | 3 | Table: Activity 4 | +---------------+---------+ 5 | | Column Name | Type | 6 | +---------------+---------+ 7 | | user_id | int | 8 | | session_id | int | 9 | | activity_date | date | 10 | | activity_type | enum | 11 | +---------------+---------+ 12 | This table may have duplicate rows. 13 | The activity_type column is an ENUM (category) of type ('open_session', 'end_session', 'scroll_down', 'send_message'). 14 | The table shows the user activities for a social media website. 15 | Note that each session belongs to exactly one user. 16 | 17 | Write a solution to find the daily active user count for a period of 30 days ending 2019-07-27 inclusively. A user was active on someday if they made at least one activity on that day. 18 | */ 19 | 20 | SELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users 21 | FROM Activity 22 | WHERE activity_date >= '2019-06-28' AND activity_date <= '2019-07-27' 23 | GROUP BY activity_date; -------------------------------------------------------------------------------- /Solutions/Problem-31.sql: -------------------------------------------------------------------------------- 1 | /* 31.Delete Duplicate Emails : 2 | 3 | Table: Person 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | id | int | 8 | | email | varchar | 9 | +-------------+---------+ 10 | id is the primary key (column with unique values) for this table. 11 | Each row of this table contains an email. The emails will not contain uppercase letters. 12 | 13 | Write a solution to delete all duplicate emails, keeping only one unique email with the smallest id. 14 | For SQL users, please note that you are supposed to write a DELETE statement and not a SELECT one. 15 | For Pandas users, please note that you are supposed to modify Person in place. 16 | After running your script, the answer shown is the Person table. The driver will first compile and run your piece of code and then show the Person table. The final order of the Person table does not matter. 17 | */ 18 | 19 | 20 | DELETE p1 FROM Person p1 21 | JOIN Person p2 22 | ON p1.email = p2.email AND p1.id > p2.id; 23 | -------------------------------------------------------------------------------- /Solutions/Problem-43.sql: -------------------------------------------------------------------------------- 1 | /*43.Friend Requests II: Who Has the Most Friends : 2 | 3 | Table: RequestAccepted 4 | +----------------+---------+ 5 | | Column Name | Type | 6 | +----------------+---------+ 7 | | requester_id | int | 8 | | accepter_id | int | 9 | | accept_date | date | 10 | +----------------+---------+ 11 | (requester_id, accepter_id) is the primary key (combination of columns with unique values) for this table. 12 | This table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted. 13 | 14 | Write a solution to find the people who have the most friends and the most friends number. 15 | The test cases are generated so that only one person has the most friends. 16 | */ 17 | 18 | WITH Friends AS ( 19 | SELECT requester_id AS id FROM RequestAccepted 20 | UNION ALL 21 | SELECT accepter_id FROM RequestAccepted 22 | ) 23 | SELECT id, COUNT(*) AS num 24 | FROM Friends 25 | GROUP BY id 26 | ORDER BY num DESC 27 | LIMIT 1; -------------------------------------------------------------------------------- /Solutions/Problem-19.sql: -------------------------------------------------------------------------------- 1 | /* 19.Monthly Transactions I : 2 | 3 | Table: Transactions 4 | +---------------+---------+ 5 | | Column Name | Type | 6 | +---------------+---------+ 7 | | id | int | 8 | | country | varchar | 9 | | state | enum | 10 | | amount | int | 11 | | trans_date | date | 12 | +---------------+---------+ 13 | id is the primary key of this table. 14 | The table has information about incoming transactions. 15 | The state column is an enum of type ["approved", "declined"]. 16 | 17 | Write an SQL query to find for each month and country, the number of transactions and their total amount, the number of approved transactions and their total amount. 18 | */ 19 | 20 | select 21 | date_format(trans_date, '%Y-%m') as month, 22 | country, 23 | count(id) as trans_count, 24 | sum(state='approved') as approved_count, 25 | sum(amount) as trans_total_amount, 26 | sum(if(state= 'approved', amount, 0)) as approved_total_amount 27 | 28 | from Transactions 29 | group by month, country -------------------------------------------------------------------------------- /Solutions/Problem-38.sql: -------------------------------------------------------------------------------- 1 | /* 38.Customers Who Bought All Products : 2 | 3 | Table: Customer 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | customer_id | int | 8 | | product_key | int | 9 | +-------------+---------+ 10 | This table may contain duplicates rows. 11 | customer_id is not NULL. 12 | product_key is a foreign key (reference column) to Product table. 13 | 14 | Table: Product 15 | +-------------+---------+ 16 | | Column Name | Type | 17 | +-------------+---------+ 18 | | product_key | int | 19 | +-------------+---------+ 20 | product_key is the primary key (column with unique values) for this table. 21 | 22 | Write a solution to report the customer ids from the Customer table that bought all the products in the Product table. 23 | */ 24 | 25 | 26 | 27 | WITH ProductCount AS ( 28 | SELECT COUNT(*) AS total_products FROM Product 29 | ) 30 | SELECT c.customer_id 31 | FROM Customer c 32 | GROUP BY c.customer_id 33 | HAVING COUNT(DISTINCT c.product_key) = (SELECT total_products FROM ProductCount); 34 | -------------------------------------------------------------------------------- /Solutions/Problem-28.sql: -------------------------------------------------------------------------------- 1 | /* 28.Employees Whose Manager Left the Company : 2 | 3 | Table: Employees 4 | +-------------+----------+ 5 | | Column Name | Type | 6 | +-------------+----------+ 7 | | employee_id | int | 8 | | name | varchar | 9 | | manager_id | int | 10 | | salary | int | 11 | +-------------+----------+ 12 | In SQL, employee_id is the primary key for this table. 13 | This table contains information about the employees, their salary, and the ID of their manager. Some employees do not have a manager (manager_id is null). 14 | 15 | Find the IDs of the employees whose salary is strictly less than $30000 and whose manager left the company. When a manager leaves the company, their information is deleted from the Employees table, but the reports still have their manager_id set to the manager that left. 16 | Return the result table ordered by employee_id. 17 | */ 18 | 19 | 20 | SELECT employee_id 21 | FROM Employees e1 22 | WHERE salary < 30000 23 | AND manager_id IS NOT NULL 24 | AND manager_id NOT IN (SELECT employee_id FROM Employees) 25 | ORDER BY employee_id; 26 | -------------------------------------------------------------------------------- /Solutions/Problem-18.sql: -------------------------------------------------------------------------------- 1 | /* 18.Percentage of Users Attended a Contest : 2 | 3 | Table: Users 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | user_id | int | 8 | | user_name | varchar | 9 | +-------------+---------+ 10 | user_id is the primary key (column with unique values) for this table. 11 | Each row of this table contains the name and the id of a user. 12 | 13 | Table: Register 14 | +-------------+---------+ 15 | | Column Name | Type | 16 | +-------------+---------+ 17 | | contest_id | int | 18 | | user_id | int | 19 | +-------------+---------+ 20 | (contest_id, user_id) is the primary key (combination of columns with unique values) for this table. 21 | Each row of this table contains the id of a user and the contest they registered into. 22 | 23 | Write a solution to find the percentage of the users registered in each contest rounded to two decimals 24 | */ 25 | 26 | SELECT contest_id, Round(COUNT(distinct user_id)*100/(SELECT COUNT(user_id)FROM Users),2) 27 | AS percentage 28 | From Register 29 | GROUP BY contest_id 30 | ORDER BY percentage DESC, contest_id -------------------------------------------------------------------------------- /Solutions/Problem-06.sql: -------------------------------------------------------------------------------- 1 | /* 6.Replace Employee ID With The Unique Identifier: 2 | 3 | Table: Employees 4 | +---------------+---------+ 5 | | Column Name | Type | 6 | +---------------+---------+ 7 | | id | int | 8 | | name | varchar | 9 | +---------------+---------+ 10 | id is the primary key (column with unique values) for this table. 11 | Each row of this table contains the id and the name of an employee in a company. 12 | 13 | Table: EmployeeUNI 14 | +---------------+---------+ 15 | | Column Name | Type | 16 | +---------------+---------+ 17 | | id | int | 18 | | unique_id | int | 19 | +---------------+---------+ 20 | (id, unique_id) is the primary key (combination of columns with unique values) for this table. 21 | Each row of this table contains the id and the corresponding unique id of an employee in the company. 22 | 23 | Write a solution to show the unique ID of each user, If a user does not have a unique ID replace just show null. 24 | Return the result table in any order. 25 | */ 26 | 27 | select en.unique_id, e.name 28 | from Employees e 29 | left join 30 | EmployeeUNI en 31 | on 32 | e.id=en.id -------------------------------------------------------------------------------- /Solutions/Problem-11.sql: -------------------------------------------------------------------------------- 1 | /* 11.Employee Bonus : 2 | 3 | Table: Employee 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | empId | int | 8 | | name | varchar | 9 | | supervisor | int | 10 | | salary | int | 11 | +-------------+---------+ 12 | empId is the column with unique values for this table. 13 | Each row of this table indicates the name and the ID of an employee in addition to their salary and the id of their manager. 14 | 15 | Table: Bonus 16 | +-------------+------+ 17 | | Column Name | Type | 18 | +-------------+------+ 19 | | empId | int | 20 | | bonus | int | 21 | +-------------+------+ 22 | empId is the column of unique values for this table. 23 | empId is a foreign key (reference column) to empId from the Employee table. 24 | Each row of this table contains the id of an employee and their respective bonus. 25 | 26 | Write a solution to report the name and bonus amount of each employee with a bonus less than 1000. 27 | */ 28 | 29 | SELECT e.name, b.bonus 30 | FROM Employee e 31 | LEFT JOIN Bonus b 32 | ON e.empID = b.empId 33 | WHERE b.bonus is null OR b.bonus <1000 -------------------------------------------------------------------------------- /Solutions/Problem-25.sql: -------------------------------------------------------------------------------- 1 | /* 25.The Number of Employees Which Report to Each Employee : 2 | 3 | Table: Employees 4 | +-------------+----------+ 5 | | Column Name | Type | 6 | +-------------+----------+ 7 | | employee_id | int | 8 | | name | varchar | 9 | | reports_to | int | 10 | | age | int | 11 | +-------------+----------+ 12 | employee_id is the column with unique values for this table. 13 | This table contains information about the employees and the id of the manager they report to. Some employees do not report to anyone (reports_to is null). 14 | 15 | For this problem, we will consider a manager an employee who has at least 1 other employee reporting to them. 16 | Write a solution to report the ids and the names of all managers, the number of employees who report directly to them, and the average age of the reports rounded to the nearest integer. 17 | */ 18 | 19 | SELECT e.employee_id, e.name, 20 | COUNT(r.employee_id) 21 | AS reports_count, ROUND(AVG(r.age)) 22 | AS average_age 23 | FROM Employees e 24 | LEFT JOIN Employees r 25 | ON e.employee_id = r.reports_to 26 | WHERE r.employee_id 27 | IS NOT NULL GROUP BY e.employee_id, e.name 28 | ORDER BY e.employee_id; -------------------------------------------------------------------------------- /Solutions/Problem-07.sql: -------------------------------------------------------------------------------- 1 | /* 7.Product Sales Analysis I : 2 | 3 | Table: Sales 4 | +-------------+-------+ 5 | | Column Name | Type | 6 | +-------------+-------+ 7 | | sale_id | int | 8 | | product_id | int | 9 | | year | int | 10 | | quantity | int | 11 | | price | int | 12 | +-------------+-------+ 13 | (sale_id, year) is the primary key (combination of columns with unique values) of this table. 14 | product_id is a foreign key (reference column) to Product table. 15 | Each row of this table shows a sale on the product product_id in a certain year. 16 | Note that the price is per unit. 17 | 18 | Table: Product 19 | +--------------+---------+ 20 | | Column Name | Type | 21 | +--------------+---------+ 22 | | product_id | int | 23 | | product_name | varchar | 24 | +--------------+---------+ 25 | product_id is the primary key (column with unique values) of this table. 26 | Each row of this table indicates the product name of each product. 27 | 28 | Write a solution to report the product_name, year, and price for each sale_id in the Sales table. 29 | Return the resulting table in any order. 30 | */ 31 | 32 | select product_name, year, price 33 | from sales s join product p 34 | on s.product_id=p.product_id; -------------------------------------------------------------------------------- /Solutions/Problem-08.sql: -------------------------------------------------------------------------------- 1 | /* 8.Customer Who Visited but Did Not Make Any Transactions : 2 | 3 | Table: Visits 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | visit_id | int | 8 | | customer_id | int | 9 | +-------------+---------+ 10 | visit_id is the column with unique values for this table. 11 | This table contains information about the customers who visited the mall. 12 | 13 | Table: Transactions 14 | +----------------+---------+ 15 | | Column Name | Type | 16 | +----------------+---------+ 17 | | transaction_id | int | 18 | | visit_id | int | 19 | | amount | int | 20 | +----------------+---------+ 21 | transaction_id is column with unique values for this table. 22 | This table contains information about the transactions made during the visit_id. 23 | 24 | Write a solution to find the IDs of the users who visited without making any transactions and the number of times they made these types of visits. 25 | Return the result table sorted in any order. 26 | */ 27 | 28 | SELECT customer_id, count(a.visit_id) as count_no_trans 29 | FROM Visits a 30 | left join Transactions b 31 | on a.visit_id = b.visit_id 32 | where b.visit_id is null 33 | GROUP BY customer_id -------------------------------------------------------------------------------- /Solutions/Problem-17.sql: -------------------------------------------------------------------------------- 1 | /* 17.Project Employees I : 2 | 3 | Table: Project 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | project_id | int | 8 | | employee_id | int | 9 | +-------------+---------+ 10 | (project_id, employee_id) is the primary key of this table. 11 | employee_id is a foreign key to Employee table. 12 | Each row of this table indicates that the employee with employee_id is working on the project with project_id. 13 | 14 | Table: Employee 15 | +------------------+---------+ 16 | | Column Name | Type | 17 | +------------------+---------+ 18 | | employee_id | int | 19 | | name | varchar | 20 | | experience_years | int | 21 | +------------------+---------+ 22 | employee_id is the primary key of this table. It's guaranteed that experience_years is not NULL. 23 | Each row of this table contains information about one employee. 24 | 25 | Write an SQL query that reports the average experience years of all the employees for each project, rounded to 2 digits. 26 | */ 27 | 28 | SELECT p.project_id, ROUND(AVG(e.experience_years), 2) AS average_years 29 | FROM Project p 30 | LEFT JOIN Employee e 31 | ON p.employee_id = e.employee_id 32 | GROUP BY p.project_id -------------------------------------------------------------------------------- /Solutions/Problem-33.sql: -------------------------------------------------------------------------------- 1 | /* 33.List the Products Ordered in a Period : 2 | 3 | Table: Products 4 | +------------------+---------+ 5 | | Column Name | Type | 6 | +------------------+---------+ 7 | | product_id | int | 8 | | product_name | varchar | 9 | | product_category | varchar | 10 | +------------------+---------+ 11 | product_id is the primary key (column with unique values) for this table. 12 | This table contains data about the company's products. 13 | 14 | Table: Orders 15 | +---------------+---------+ 16 | | Column Name | Type | 17 | +---------------+---------+ 18 | | product_id | int | 19 | | order_date | date | 20 | | unit | int | 21 | +---------------+---------+ 22 | This table may have duplicate rows. 23 | product_id is a foreign key (reference column) to the Products table. 24 | unit is the number of products ordered in order_date. 25 | 26 | Write a solution to get the names of products that have at least 100 units ordered in February 2020 and their amount. 27 | */ 28 | 29 | SELECT p.product_name, SUM(o.unit) AS unit 30 | FROM Products p 31 | JOIN Orders o ON p.product_id = o.product_id 32 | WHERE o.order_date BETWEEN '2020-02-01' AND '2020-02-29' 33 | GROUP BY p.product_name 34 | HAVING SUM(o.unit) >= 100; 35 | -------------------------------------------------------------------------------- /Solutions/Problem-36.sql: -------------------------------------------------------------------------------- 1 | /* 36.Queries Quality and Percentage : 2 | 3 | Table: Queries 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | query_name | varchar | 8 | | result | varchar | 9 | | position | int | 10 | | rating | int | 11 | +-------------+---------+ 12 | This table may have duplicate rows. 13 | This table contains information collected from some queries on a database. 14 | The position column has a value from 1 to 500. 15 | The rating column has a value from 1 to 5. Query with rating less than 3 is a poor query. 16 | 17 | We define query quality as: 18 | The average of the ratio between query rating and its position. 19 | 20 | We also define poor query percentage as: 21 | The percentage of all queries with rating less than 3. 22 | Write a solution to find each query_name, the quality and poor_query_percentage. 23 | Both quality and poor_query_percentage should be rounded to 2 decimal places. 24 | */ 25 | 26 | WITH QueryQuality AS ( 27 | SELECT 28 | query_name, 29 | ROUND(AVG(rating * 1.0 / position), 2) AS quality, 30 | ROUND(100.0 * SUM(CASE WHEN rating < 3 THEN 1 ELSE 0 END) / COUNT(*), 2) AS poor_query_percentage 31 | FROM Queries 32 | GROUP BY query_name 33 | ) 34 | SELECT * FROM QueryQuality; 35 | -------------------------------------------------------------------------------- /Solutions/Problem-42.sql: -------------------------------------------------------------------------------- 1 | /* 42.Count Salary Categories : 2 | 3 | Table: Accounts 4 | +-------------+------+ 5 | | Column Name | Type | 6 | +-------------+------+ 7 | | account_id | int | 8 | | income | int | 9 | +-------------+------+ 10 | account_id is the primary key (column with unique values) for this table. 11 | Each row contains information about the monthly income for one bank account. 12 | 13 | Write a solution to calculate the number of bank accounts for each salary category. The salary categories are: 14 | 15 | "Low Salary": All the salaries strictly less than $20000. 16 | "Average Salary": All the salaries in the inclusive range [$20000, $50000]. 17 | "High Salary": All the salaries strictly greater than $50000. 18 | The result table must contain all three categories. If there are no accounts in a category, return 0. 19 | 20 | Return the result table in any order. 21 | */ 22 | 23 | 24 | SELECT 'Low Salary' AS category, 25 | COUNT(*) AS accounts_count 26 | FROM Accounts 27 | WHERE income < 20000 28 | 29 | UNION ALL 30 | 31 | SELECT 'Average Salary' AS category, 32 | COUNT(*) AS accounts_count 33 | FROM Accounts 34 | WHERE income BETWEEN 20000 AND 50000 35 | 36 | UNION ALL 37 | 38 | SELECT 'High Salary' AS category, 39 | COUNT(*) AS accounts_count 40 | FROM Accounts 41 | WHERE income > 50000; 42 | -------------------------------------------------------------------------------- /Solutions/Problem-40.sql: -------------------------------------------------------------------------------- 1 | /* 40.Investments in 2016 : 2 | 3 | Table: Insurance 4 | +-------------+-------+ 5 | | Column Name | Type | 6 | +-------------+-------+ 7 | | pid | int | 8 | | tiv_2015 | float | 9 | | tiv_2016 | float | 10 | | lat | float | 11 | | lon | float | 12 | +-------------+-------+ 13 | pid is the primary key (column with unique values) for this table. 14 | Each row of this table contains information about one policy where: 15 | pid is the policyholder's policy ID. 16 | tiv_2015 is the total investment value in 2015 and tiv_2016 is the total investment value in 2016. 17 | lat is the latitude of the policy holder's city. It's guaranteed that lat is not NULL. 18 | lon is the longitude of the policy holder's city. It's guaranteed that lon is not NULL. 19 | 20 | Write a solution to report the sum of all total investment values in 2016 tiv_2016, for all policyholders who: 21 | have the same tiv_2015 value as one or more other policyholders, and 22 | are not located in the same city as any other policyholder (i.e., the (lat, lon) attribute pairs must be unique). 23 | */ 24 | 25 | 26 | SELECT ROUND(SUM(tiv_2016), 2) AS tiv_2016 27 | FROM Insurance 28 | WHERE tiv_2015 IN ( 29 | SELECT tiv_2015 FROM Insurance 30 | GROUP BY tiv_2015 31 | HAVING COUNT(*) > 1 32 | ) 33 | AND (lat, lon) IN ( 34 | SELECT lat, lon FROM Insurance 35 | GROUP BY lat, lon 36 | HAVING COUNT(*) = 1 37 | ); 38 | -------------------------------------------------------------------------------- /Solutions/Problem-26.sql: -------------------------------------------------------------------------------- 1 | /* 26.Primary Department for Each Employee : 2 | 3 | Table: Employee 4 | +---------------+---------+ 5 | | Column Name | Type | 6 | +---------------+---------+ 7 | | employee_id | int | 8 | | department_id | int | 9 | | primary_flag | varchar | 10 | +---------------+---------+ 11 | (employee_id, department_id) is the primary key (combination of columns with unique values) for this table. 12 | employee_id is the id of the employee. 13 | department_id is the id of the department to which the employee belongs. 14 | primary_flag is an ENUM (category) of type ('Y', 'N'). If the flag is 'Y', the department is the primary department for the employee. If the flag is 'N', the department is not the primary. 15 | 16 | Employees can belong to multiple departments. When the employee joins other departments, they need to decide which department is their primary department. Note that when an employee belongs to only one department, their primary column is 'N'. 17 | 18 | Write a solution to report all the employees with their primary department. For employees who belong to one department, report their only department. 19 | */ 20 | 21 | 22 | SELECT employee_id, department_id 23 | FROM Employee 24 | WHERE primary_flag = 'Y' 25 | OR ( 26 | primary_flag = 'N' 27 | AND employee_id NOT IN ( 28 | SELECT employee_id 29 | FROM Employee 30 | WHERE primary_flag = 'Y' 31 | ) 32 | ); 33 | -------------------------------------------------------------------------------- /Solutions/Problem-41.sql: -------------------------------------------------------------------------------- 1 | /*41.Last Person to Fit in the Bus : 2 | 3 | Table: Queue 4 | +-------------+---------+ 5 | | Column Name | Type | 6 | +-------------+---------+ 7 | | person_id | int | 8 | | person_name | varchar | 9 | | weight | int | 10 | | turn | int | 11 | +-------------+---------+ 12 | person_id column contains unique values. 13 | This table has the information about all people waiting for a bus. 14 | The person_id and turn columns will contain all numbers from 1 to n, where n is the number of rows in the table. 15 | turn determines the order of which the people will board the bus, where turn=1 denotes the first person to board and turn=n denotes the last person to board. 16 | weight is the weight of the person in kilograms. 17 | 18 | There is a queue of people waiting to board a bus. However, the bus has a weight limit of 1000 kilograms, so there may be some people who cannot board. 19 | 20 | Write a solution to find the person_name of the last person that can fit on the bus without exceeding the weight limit. The test cases are generated such that the first person does not exceed the weight limit. 21 | */ 22 | 23 | 24 | WITH CumulativeWeight AS ( 25 | SELECT 26 | person_name, 27 | weight, 28 | SUM(weight) OVER (ORDER BY turn) AS total_weight 29 | FROM Queue 30 | ) 31 | SELECT person_name 32 | FROM CumulativeWeight 33 | WHERE total_weight <= 1000 34 | ORDER BY total_weight DESC 35 | LIMIT 1; 36 | -------------------------------------------------------------------------------- /Solutions/Problem-39.sql: -------------------------------------------------------------------------------- 1 | /*39.Immediate Food Delivery II: 2 | 3 | Table: Delivery 4 | +-----------------------------+---------+ 5 | | Column Name | Type | 6 | +-----------------------------+---------+ 7 | | delivery_id | int | 8 | | customer_id | int | 9 | | order_date | date | 10 | | customer_pref_delivery_date | date | 11 | +-----------------------------+---------+ 12 | delivery_id is the column of unique values of this table. 13 | The table holds information about food delivery to customers that make orders at some date and specify a preferred delivery date (on the same order date or after it). 14 | 15 | If the customer's preferred delivery date is the same as the order date, then the order is called immediate; otherwise, it is called scheduled. 16 | 17 | The first order of a customer is the order with the earliest order date that the customer made. It is guaranteed that a customer has precisely one first order. 18 | 19 | Write a solution to find the percentage of immediate orders in the first orders of all customers, rounded to 2 decimal places. 20 | */ 21 | 22 | 23 | WITH FirstOrders AS ( 24 | SELECT customer_id, 25 | MIN(order_date) AS first_order_date 26 | FROM Delivery 27 | GROUP BY customer_id 28 | ) 29 | SELECT 30 | ROUND(100 * SUM(CASE WHEN d.order_date = d.customer_pref_delivery_date THEN 1 ELSE 0 END) / COUNT(*), 2) AS immediate_percentage 31 | FROM Delivery d 32 | JOIN FirstOrders f 33 | ON d.customer_id = f.customer_id AND d.order_date = f.first_order_date; 34 | -------------------------------------------------------------------------------- /Solutions/Problem-45.sql: -------------------------------------------------------------------------------- 1 | /*45.Restaurant Growth : 2 | 3 | Table: Customer 4 | +---------------+---------+ 5 | | Column Name | Type | 6 | +---------------+---------+ 7 | | customer_id | int | 8 | | name | varchar | 9 | | visited_on | date | 10 | | amount | int | 11 | +---------------+---------+ 12 | 13 | In SQL,(customer_id, visited_on) is the primary key for this table. 14 | This table contains data about customer transactions in a restaurant. 15 | visited_on is the date on which the customer with ID (customer_id) has visited the restaurant. 16 | amount is the total paid by a customer. 17 | 18 | You are the restaurant owner and you want to analyze a possible expansion (there will be at least one customer every day). 19 | Compute the moving average of how much the customer paid in a seven days window (i.e., current day + 6 days before). average_amount should be rounded to two decimal places. 20 | 21 | */ 22 | 23 | WITH Aggregated AS ( 24 | SELECT visited_on, SUM(amount) AS total_amount 25 | FROM Customer 26 | GROUP BY visited_on 27 | ), 28 | MovingAverage AS ( 29 | SELECT 30 | a1.visited_on, 31 | SUM(a2.total_amount) AS amount, 32 | ROUND(AVG(a2.total_amount), 2) AS average_amount 33 | FROM Aggregated a1 34 | JOIN Aggregated a2 35 | ON a2.visited_on BETWEEN DATE_SUB(a1.visited_on, INTERVAL 6 DAY) AND a1.visited_on 36 | GROUP BY a1.visited_on 37 | HAVING COUNT(a2.visited_on) = 7 38 | ) 39 | SELECT visited_on, amount, average_amount 40 | FROM MovingAverage 41 | ORDER BY visited_on; 42 | -------------------------------------------------------------------------------- /Solutions/Problem-16.sql: -------------------------------------------------------------------------------- 1 | /* 16.Average Selling Price: 2 | 3 | Table: Prices 4 | +---------------+---------+ 5 | | Column Name | Type | 6 | +---------------+---------+ 7 | | product_id | int | 8 | | start_date | date | 9 | | end_date | date | 10 | | price | int | 11 | +---------------+---------+ 12 | (product_id, start_date, end_date) is the primary key (combination of columns with unique values) for this table. 13 | Each row of this table indicates the price of the product_id in the period from start_date to end_date. 14 | For each product_id there will be no two overlapping periods. That means there will be no two intersecting periods for the same product_id. 15 | 16 | Table: UnitsSold 17 | +---------------+---------+ 18 | | Column Name | Type | 19 | +---------------+---------+ 20 | | product_id | int | 21 | | purchase_date | date | 22 | | units | int | 23 | +---------------+---------+ 24 | This table may contain duplicate rows. 25 | Each row of this table indicates the date, units, and product_id of each product sold. 26 | 27 | Write a solution to find the average selling price for each product. average_price should be rounded to 2 decimal places. If a product does not have any sold units, its average selling price is assumed to be 0. 28 | */ 29 | 30 | SELECT p.product_id, IFNULL(ROUND(SUM(p.price*u.units)/SUM(u.units),2),0) AS average_price 31 | FROM Prices P 32 | LEFT JOIN UnitsSold u 33 | ON p.product_id=u.product_id 34 | AND u.purchase_date >= p.start_date 35 | AND u.purchase_date <= p.end_date 36 | GROUP BY p.product_id -------------------------------------------------------------------------------- /Solutions/Problem-14.sql: -------------------------------------------------------------------------------- 1 | /* 14.Confirmation Rate : 2 | 3 | Table: Signups 4 | +----------------+----------+ 5 | | Column Name | Type | 6 | +----------------+----------+ 7 | | user_id | int | 8 | | time_stamp | datetime | 9 | +----------------+----------+ 10 | user_id is the column of unique values for this table. 11 | Each row contains information about the signup time for the user with ID user_id. 12 | 13 | Table: Confirmations 14 | +----------------+----------+ 15 | | Column Name | Type | 16 | +----------------+----------+ 17 | | user_id | int | 18 | | time_stamp | datetime | 19 | | action | ENUM | 20 | +----------------+----------+ 21 | (user_id, time_stamp) is the primary key (combination of columns with unique values) for this table. 22 | user_id is a foreign key (reference column) to the Signups table. 23 | action is an ENUM (category) of the type ('confirmed', 'timeout') 24 | Each row of this table indicates that the user with ID user_id requested a confirmation message at time_stamp and that confirmation message was either confirmed ('confirmed') or expired without confirming ('timeout'). 25 | 26 | The confirmation rate of a user is the number of 'confirmed' messages divided by the total number of requested confirmation messages. The confirmation rate of a user that did not request any confirmation messages is 0. Round the confirmation rate to two decimal places. 27 | Write a solution to find the confirmation rate of each user. 28 | */ 29 | 30 | SELECT s.user_id, IFNULL(ROUND(SUM(action = 'confirmed')/COUNT(*), 2), 0.00) AS confirmation_rate 31 | FROM Signups s 32 | LEFT JOIN Confirmations c 33 | ON s.user_id = c.user_id 34 | GROUP BY s.user_id -------------------------------------------------------------------------------- /Solutions/Problem-44.sql: -------------------------------------------------------------------------------- 1 | /* 44.Department Top Three Salaries : 2 | 3 | Table: Employee 4 | +--------------+---------+ 5 | | Column Name | Type | 6 | +--------------+---------+ 7 | | id | int | 8 | | name | varchar | 9 | | salary | int | 10 | | departmentId | int | 11 | +--------------+---------+ 12 | id is the primary key (column with unique values) for this table. 13 | departmentId is a foreign key (reference column) of the ID from the Department table. 14 | Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department. 15 | 16 | Table: Department 17 | +-------------+---------+ 18 | | Column Name | Type | 19 | +-------------+---------+ 20 | | id | int | 21 | | name | varchar | 22 | +-------------+---------+ 23 | id is the primary key (column with unique values) for this table. 24 | Each row of this table indicates the ID of a department and its name. 25 | 26 | A company's executives are interested in seeing who earns the most money in each of the company's departments. A high earner in a department is an employee who has a salary in the top three unique salaries for that department. 27 | Write a solution to find the employees who are high earners in each of the departments. 28 | */ 29 | 30 | 31 | WITH RankedSalaries AS ( 32 | SELECT 33 | e.id, 34 | e.name AS Employee, 35 | e.salary AS Salary, 36 | d.name AS Department, 37 | DENSE_RANK() OVER (PARTITION BY e.departmentId ORDER BY e.salary DESC) AS rnk 38 | FROM Employee e 39 | JOIN Department d ON e.departmentId = d.id 40 | ) 41 | SELECT Department, Employee, Salary 42 | FROM RankedSalaries 43 | WHERE rnk <= 3; 44 | -------------------------------------------------------------------------------- /Solutions/Problem-12.sql: -------------------------------------------------------------------------------- 1 | /* 12.Students and Examinations : 2 | 3 | Table: Students 4 | +---------------+---------+ 5 | | Column Name | Type | 6 | +---------------+---------+ 7 | | student_id | int | 8 | | student_name | varchar | 9 | +---------------+---------+ 10 | student_id is the primary key (column with unique values) for this table. 11 | Each row of this table contains the ID and the name of one student in the school. 12 | 13 | Table: Subjects 14 | +--------------+---------+ 15 | | Column Name | Type | 16 | +--------------+---------+ 17 | | subject_name | varchar | 18 | +--------------+---------+ 19 | subject_name is the primary key (column with unique values) for this table. 20 | Each row of this table contains the name of one subject in the school. 21 | 22 | Table: Examinations 23 | +--------------+---------+ 24 | | Column Name | Type | 25 | +--------------+---------+ 26 | | student_id | int | 27 | | subject_name | varchar | 28 | +--------------+---------+ 29 | There is no primary key (column with unique values) for this table. It may contain duplicates. 30 | Each student from the Students table takes every course from the Subjects table. 31 | Each row of this table indicates that a student with ID student_id attended the exam of subject_name. 32 | 33 | Write a solution to find the number of times each student attended each exam. 34 | Return the result table ordered by student_id and subject_name. 35 | */ 36 | 37 | SELECT s.student_id , s.student_name , sub.subject_name, 38 | COUNT(e.subject_name) AS attended_exams 39 | FROM Students s 40 | CROSS JOIN Subjects sub 41 | LEFT JOIN Examinations e 42 | ON s.student_id = e.student_id AND sub.subject_name=e.subject_name 43 | GROUP BY s.student_id , s.student_name , sub.subject_name 44 | ORDER BY s.student_id , sub.subject_name -------------------------------------------------------------------------------- /Solutions/Problem-10.sql: -------------------------------------------------------------------------------- 1 | /* 10.Average Time of Process per Machine: 2 | 3 | Table: Activity 4 | +----------------+---------+ 5 | | Column Name | Type | 6 | +----------------+---------+ 7 | | machine_id | int | 8 | | process_id | int | 9 | | activity_type | enum | 10 | | timestamp | float | 11 | +----------------+---------+ 12 | The table shows the user activities for a factory website. 13 | (machine_id, process_id, activity_type) is the primary key (combination of columns with unique values) of this table. 14 | machine_id is the ID of a machine. 15 | process_id is the ID of a process running on the machine with ID machine_id. 16 | activity_type is an ENUM (category) of type ('start', 'end'). 17 | timestamp is a float representing the current time in seconds. 18 | 'start' means the machine starts the process at the given timestamp and 'end' means the machine ends the process at the given timestamp. 19 | The 'start' timestamp will always be before the 'end' timestamp for every (machine_id, process_id) pair. 20 | It is guaranteed that each (machine_id, process_id) pair has a 'start' and 'end' timestamp. 21 | 22 | There is a factory website that has several machines each running the same number of processes. Write a solution to find the average time each machine takes to complete a process. 23 | The time to complete a process is the 'end' timestamp minus the 'start' timestamp. The average time is calculated by the total time to complete every process on the machine divided by the number of processes that were run. 24 | The resulting table should have the machine_id along with the average time as processing_time, which should be rounded to 3 decimal places. 25 | Return the result table in any order. 26 | */ 27 | 28 | SELECT a1.machine_id , ROUND(AVG(a2.timestamp - a1.timestamp),3) 29 | AS processing_time 30 | FROM Activity a1 31 | INNER JOIN Activity a2 32 | ON a1.process_id=a2.process_id 33 | AND a1.machine_id=a2.machine_id 34 | AND a1.timestamp < a2.timestamp 35 | GROUP BY a1.machine_id --------------------------------------------------------------------------------