1) Leetcode SQL 50 Challenge
1) Leetcode SQL 50 Challenge
Yang dibahas
Select 5
) Basic Join 9
d Subqueries 7
Level
64% 34% 2%
Cek soalnya disini >> https://leetcode.com/studyplan/top-sql-50/
1
Select
Soal Level
Pertanyaan
Write a solution to find the ids of products that are both low fat and recyclable. Return the
result table in any order. The result format is in the following example.
Query MySQL
Pertanyaan
Find the names of the customer that are not referred by the customer with id = 2.
Return the result table in any order. The result format is in the following example.
Query MySQL
Pertanyaan
A country is big if&
4 it has an area of at least three million (i.e., 3000000 km2), o5
4 it has a population of at least twenty-five million (i.e., 25000000).
Write a solution to find the name, population, and area of the big countries.
Return the result table in any order. The result format is in the following example.
Query MySQL
SELECT name, population, area FROM World
Query MySQL
SELECT DISTINCT author_id AS id FROM Views
Pertanyaan
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.
Query MySQL
Pertanyaan
Write a solution to show the unique ID of each user, If a user does not have a unique ID replace
just show null. Return the result table in any order.
Query MySQL
FROM Employees
Pertanyaan
Write a solution to report the product_name, year, and price for each sale_id in the Sales
table. Return the resulting table in any order. The result format is in the following example.
Query MySQL
FROM Sales
Query MySQL
SELECT Visits.customer_id, COUNT(Visits.visit_id)
AS count_no_trans
FROM Visits
GROUP BY Visits.customer_id
Rising Temperature
Pertanyaan
Write a solution to find all dates' Id with higher temperatures compared to its previous dates
(yesterday). Return the result table in any order.
Query MySQL
SELECT nowDay.id FROM Weather nowDay
Query MySQL
SELECT A1.machine_id,
ROUND(AVG(A1.timestamp-A2.timestamp), 3)
AS processing_time
FROM Activity A1
GROUP BY A1.machine_id
Students and Examinations
Pertanyaan
Write a solution to find the number of times each student attended each exam.
Query MySQL
Subjects.subject_name,
COUNT(Examinations.subject_name)
AS attended_exams
FROM Students
ON Students.student_id = Examinations.student_id
Examinations.subject_name
Pertanyaan
Write a solution to report the name and bonus amount of each employee with a bonus less
than 1000. Return the result table in any order.
Query MySQL
SELECT Employee.name, Bonus.bonus
FROM Employee
Pertanyaan
Write a solution to find managers with at least five direct reports.
Query MySQL
SELECT E1.name FROM Employee E1
Pertanyaan
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.
Return the result table in any order. The result format is in the following example.
Query MySQL
SELECT Signups.user_id,
AS confirmation_rate
FROM Signups
ON Signups.user_id = Confirmations.user_id
GROUP BY Signups.user_id
3 Basic
Aggregate
Functions
Soal Level
Pertanyaan
Write a solution to report the movies with an odd-numbered ID and a description that is
not "boring". Return the result table ordered by rating in descending order.
Query MySQL
SELECT * FROM Cinema
Pertanyaan
Write a solution to find the average selling price for each product. average_price should
Query MySQL
SELECT Prices.product_id,
AS average_price
FROM Prices
GROUP BY Prices.product_id
Project Employees I
Pertanyaan
Write an SQL query that reports the average experience years of all the employees for
each project, rounded to 2 digits. Return the result table in any order.
Query MySQL
SELECT Project.project_id,
ROUND(AVG(Employee.experience_years), 2)
AS average_years
FROM Project
ON Project.employee_id = Employee.employee_id
GROUP BY Project.project_id
Percentage of Users Attended a Contest
Pertanyaan
Write a solution to find the percentage of the users registered in each contest rounded
to two decimals. Return the result table ordered by percentage in descending order. In
case of a tie, order it by contest_id in ascending order.
Query MySQL
SELECT contest_id,
ROUND(
FROM Users))
, 2) AS percentage
FROM Register
GROUP BY contest_id
Pertanyaan
We define query quality as$
+ The average of the ratio between query rating and its position.
Return the result table in any order. The result format is in the following example.
Query MySQL
SELECT query_name,
FROM Queries
GROUP BY query_name
Monthly Transactions I
Pertanyaan
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.
Query MySQL
country,
COUNT(*) AS trans_count,
SUM(amount) AS trans_total_amount,
SUM(IF(state='approved',amount,0)) AS approved_total_amount
FROM Transactions
Pertanyaan
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.
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.
Write a solution to find the percentage of immediate orders in the first orders of all
customers, rounded to 2 decimal places.
Query MySQL
SELECT ROUND(
FROM Delivery
GROUP BY customer_id
)
Game Play Analysis IV
Pertanyaan
Write a solution to report the fraction of players that logged in again on the day after the
day they first logged in, rounded to 2 decimal places. In other words, you need to count
the number of players that logged in for at least two consecutive days starting from their
first login date, then divide that number by the total number of players.
Query MySQL
SELECT ROUND(
COUNT(DISTINCT player_id) /
FROM Activity)
FROM Activity
GROUP BY player_id
)
4 Sorting
and
Grouping
Soal Level
Pertanyaan
Write a solution to calculate the number of unique subjects each teacher teaches in the
university. Return the result table in any order.
Query MySQL
SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt
FROM Teacher
GROUP BY teacher_id
Pertanyaan
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. Return the result table in any order.
Query MySQL
SELECT activity_date AS day,
FROM Activity
GROUP BY activity_date
Pertanyaan
Write a solution to select the product id, year, quantity, and price for the first year of
Query MySQL
FROM Sales
FROM Sales
GROUP BY product_id
)
Classes More Than 5 Students
Pertanyaan
Write a solution to find all the classes that have at least five students.
Query MySQL
SELECT class FROM Courses
Pertanyaan
Write a solution that will, for each user, return the number of followers.
Query MySQL
SELECT user_id,
COUNT(follower_id) AS followers_count
FROM Followers
GROUP BY user_id
Find the largest single number. If there is no single number, report null.
Query MySQL
SELECT IF(COUNT(num) = 1, num, NULL) AS num
FROM MyNumbers
GROUP BY num
LIMIT 1
Customers Who Bought All Products
Pertanyaan
Write a solution to report the customer ids from the Customer table that bought all the
products in the Product table.
Query MySQL
SELECT customer_id FROM Customer
Select
and Joins
Soal Level
Pertanyaan
For this problem, we will consider a manager an employee who has at least 1 other
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
Query MySQL
FROM Employees AS E1
INNER JOIN (
SELECT reports_to,
COUNT(reports_to) AS reports_count,
ROUND(AVG(age), 0) AS average_age
FROM Employees
GROUP BY reports_to
) AS E2 ON E1.employee_id = E2.reports_to
ORDER BY E1.employee_id
Primary Department for Each Employee
Pertanyaan
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'.
Write a solution to report all the employees with their primary department. For employees
who belong to one department, report their only department.
Return the result table in any order. The result format is in the following example.
Query MySQL
SELECT employee_id, department_id
FROM Employee
SELECT employee_id
FROM Employee
)
Triangle Judgement
Pertanyaan
Report for every three line segments whether they can form a triangle.
Query MySQL
SELECT *,
IF(x+y > z AND x+z > y AND y+z > x, 'Yes', 'No') AS triangle
FROM Triangle
Consecutive Numbers
Pertanyaan
Find all numbers that appear at least three times consecutively.
Query MySQL
WITH cte AS (
SELECT num,
FROM Logs
FROM cte
Pertanyaan
Write a solution to find the prices of all products on 2019-08-16. Assume the price of all
products before any change is 10. Return the result table in any order.
Query MySQL
WITH cte AS (
FROM Products
AND cte.rowNum = 1
Last Person to Fit in the Bus
Pertanyaan
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.
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.
Query MySQL
WITH cte AS (
FROM Queue
LIMIT 1
Count Salary Categories
Pertanyaan
Write a solution to calculate the number of bank accounts for each salary category. The
"Average Salary": All the salaries in the inclusive range [$20000, $50000]5
The result table must contain all three categories. If there are no accounts in a category,
return 0. Return the result table in any order. The result format is in the following example.
Query MySQL
FROM Accounts
UNION ALL
FROM Accounts
UNION ALL
FROM Accounts
Soal Level
Query MySQL
SELECT employee_id FROM Employees
SELECT employee_id
FROM Employees
ORDER BY employee_id
Exchange Seats
Pertanyaan
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.
Query MySQL
SELECT CASE
WHEN id % 2 = 1 THEN id + 1
ELSE id - 1
END AS id,
student
FROM Seat
ORDER BY id ASC
Movie Rating
Pertanyaan
Write a solution to
- Find the name of the user who has rated the greatest number of movies. In case of a
tie, return the lexicographically smaller user name
- Find the movie name with the highest average rating in February 2020. In case of a tie,
return the lexicographically smaller movie name.
Query MySQL
(SELECT name AS results FROM movieRating
GROUP BY user_id
LIMIT 1)
UNION ALL
GROUP BY movie_id
LIMIT 1)
Restaurant Growth
Pertanyaan
You are the restaurant owner and you want to analyze a possible expansion (there will be
at least one customer every day).
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. Return the result table ordered by visited_on in ascending order.
Query MySQL
WITH cte AS (
SELECT visited_on,
FROM Customer
ROUND(amount / 7, 2) AS average_amount
FROM cte
ORDER BY visited_on;
Pertanyaan
Write a solution to find the people who have the most friends and the most friends
number. The test cases are generated so that only one person has the most friends.
Query MySQL
SELECT id, COUNT(*) AS num
FROM (
UNION ALL
) AS friend_count
GROUP BY id
LIMIT 1
Investments in 2016
Pertanyaan
Write a solution to report the sum of all total investment values in 2016 tiv_2016, for all
policyholders who
have the same tiv_2015 value as one or more other policyholders, an
are not located in the same city as any other policyholder (i.e., the (lat, lon) attribute
pairs must be unique).
Query MySQL
SELECT ROUND(SUM(a.tiv_2016), 2) AS tiv_2016
FROM Insurance a
WHERE a.tiv_2015 IN (
);
Department Top Three Salaries
Pertanyaan
A company's executives are interested in seeing who earns the most money in each of
Write a solution to find the employees who are high earners in each of the departments.
Query MySQL
WITH cte AS (
Employee.name AS Employee,
Employee.salary AS Salary,
FROM cte
String
Functions
Soal Level
Pertanyaan
Write a solution to fix the names so that only the first character is uppercase and the rest
are lowercase.
Query MySQL
SELECT user_id,
CONCAT(
ORDER BY user_id
Patients With a Condition
Pertanyaan
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.
Query MySQL
SELECT * FROM Patients
ORDER BY patient_id
Delete Duplicate Emails
Pertanyaan
Write a solution to delete all duplicate emails, keeping only one unique email with the
smallest id.
For SQL users, please note that you are supposed to write a DELETE statement and not a
SELECT one.
For Pandas users, please note that you are supposed to modify Person in place.
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.
Query MySQL
DELETE P1
FROM person P1
Pertanyaan
Write a solution to find the second highest salary from the Employee table. If there is no
second highest salary, return null (return None in Pandas).
Query MySQL
FROM Employee
Pertanyaan
Write a solution to find for each date the number of different products sold and their
names.
The sold products names for each date should be sorted lexicographically.
Query MySQL
SELECT sell_date,
FROM Activities
GROUP BY sell_date
ORDER BY sell_date
Pertanyaan
Write a solution to get the names of products that have at least 100 units ordered in
February 2020 and their amount. Return the result table in any order.
Query MySQL
SELECT P.product_name,
SUM(O.unit) AS unit
FROM Products AS P
Query MySQL
select * from Users
Belajar.
https://github.com/dipintoo