Leetcode
SQL 50 Study Plan
50 pertanyaan SQL beserta jawabannya dari tingkat
dasar hingga menengah. Wajib dipahami!
Yang dibahas
Select Join Aggregate Subqueries
Sorting & Grouping String Functions
Daftar Isi
Materi Jumlah Soal
Select 5
) Basic Join 9
5 Basic Aggregate Functions 8
C Sorting and Grouping 7
Z Advanced Select and Joins 7
d Subqueries 7
u Advanced String Functions / Regex 7
/ Clause
Level
Easy Medium Hard
64% 34% 2%
Cek soalnya disini >> https://leetcode.com/studyplan/top-sql-50/
1
Select
Soal Level
"! Recyclable and Low Fat Products Easy
.! Find Customer Referee Easy
8! Big Countries Easy
H! Article Views I Easy
\! Invalid Tweets Easy
Recyclable and Low Fat Products
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
SELECT product_id FROM Products
WHERE (low_fats = 'Y' AND recyclable = 'Y')
Find Customer Referee
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
SELECT name FROM Customer
WHERE (referee_id != 2 OR referee_id IS NULL)
Big Countries
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
WHERE (population >= 25000000 OR area >= 3000000)
Article Views I
Pertanyaan
Write a solution to find all the authors that viewed at least one of their own articles.
Return the result table sorted by id in ascending order.
The result format is in the following example.
Query MySQL
SELECT DISTINCT author_id AS id FROM Views
WHERE author_id = viewer_id
ORDER BY author_id ASC
Invalid Tweets
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.
Return the result table in any order.
The result format is in the following example.
Query MySQL
SELECT tweet_id FROM Tweets
WHERE char_length(content) > 15
2 Basic Join
Soal Level
,* Replace Employee ID With The Unique Easy
Identifier
D* Product Sales Analysis I Easy
V* Customer Who Visited but Did Not Easy
Make Any Transactions
o* Rising Temperature Easy
* Average Time of Process per Machine Easy
* Students and Examinations Medium
* Employee Bonus Easy
·* Managers with at Least 5 Direct Medium
Reports
Å* Confirmation Rate Medium
Replace Employee ID With The Unique
Identifier
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.
The result format is in the following example.
Query MySQL
SELECT EmployeeUNI.unique_id, Employees.name
FROM Employees
LEFT JOIN EmployeeUNI ON Employees.id = EmployeeUNI.id
Product Sales Analysis I
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
SELECT Product.product_name, Sales.year, Sales.price
FROM Sales
LEFT JOIN Product ON Sales.product_id = Product.product_id
Customer Who Visited but Did Not
Make Any Transactions
Pertanyaan
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. Return the result table sorted in any
order. The result format is in the following example.
Query MySQL
SELECT Visits.customer_id, COUNT(Visits.visit_id)
AS count_no_trans
FROM Visits
LEFT JOIN Transactions ON Visits.visit_id = Transactions.visit_id
WHERE Transactions.transaction_id IS NULL
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.
The result format is in the following example.
Query MySQL
SELECT nowDay.id FROM Weather nowDay
LEFT JOIN Weather prevDay
ON nowDay.recordDate = prevDay.recordDate + INTERVAL 1 DAY
WHERE nowDay.temperature > prevDay.temperature;
Average Time of Process per Machine
Pertanyaan
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. 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. The resulting table should have the machine_id along with the average
time as processing_time, which should be rounded to 3 decimal places. Return the result table in
any order. The result format is in the following example.
Query MySQL
SELECT A1.machine_id,
ROUND(AVG(A1.timestamp-A2.timestamp), 3)
AS processing_time
FROM Activity A1
LEFT JOIN Activity A2 ON A1.machine_id = A2.machine_id
AND A1.process_id = A2.process_id
WHERE A1.timestamp > A2.timestamp
GROUP BY A1.machine_id
Students and Examinations
Pertanyaan
Write a solution to find the number of times each student attended each exam.
Return the result table ordered by student_id and subject_name.
The result format is in the following example.
Query MySQL
SELECT Students.student_id, Students.student_name,
Subjects.subject_name,
COUNT(Examinations.subject_name)
AS attended_exams
FROM Students
INNER JOIN Subjects ON 1=1
LEFT JOIN Examinations
ON Students.student_id = Examinations.student_id
AND Subjects.subject_name = Examinations.subject_name
GROUP BY Students.student_id, Subjects.subject_name,
Examinations.subject_name
ORDER BY Students.student_id, Subjects.subject_name
Employee Bonus
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.
The result format is in the following example.
Query MySQL
SELECT Employee.name, Bonus.bonus
FROM Employee
LEFT JOIN Bonus ON Employee.empId = Bonus.empId
WHERE Bonus.bonus < 1000 OR Bonus.bonus IS NULL
Managers with at Least 5 Direct Reports
Pertanyaan
Write a solution to find managers with at least five direct reports.
Return the result table in any order.
The result format is in the following example.
Query MySQL
SELECT E1.name FROM Employee E1
INNER JOIN Employee E2 ON E1.id = E2.managerId
GROUP BY E1.name, E2.managerId
HAVING COUNT(E2.managerId) >= 5
Confirmation Rate
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.
Write a solution to find the confirmation rate of each user.
Return the result table in any order. The result format is in the following example.
Query MySQL
SELECT Signups.user_id,
ROUND(IFNULL(AVG(Confirmations.action = 'confirmed') ,0) , 2)
AS confirmation_rate
FROM Signups
LEFT JOIN Confirmations
ON Signups.user_id = Confirmations.user_id
GROUP BY Signups.user_id
3 Basic
Aggregate
Functions
Soal Level
'# Not Boring Movies Easy
8# Average Selling Price Easy
D# Project Employees I Easy
^# Percentage of Users Attended a Contest Easy
p# Queries Quality and Percentage Easy
# Monthly Transactions I Medium
# Immediate Food Delivery II Medium
¢# Game Play Analysis IV Medium
Not Boring Movies
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.
The result format is in the following example.
Query MySQL
SELECT * FROM Cinema
WHERE description != "boring" AND id % 2 != 0
ORDER BY rating DESC
Average Selling Price
Pertanyaan
Write a solution to find the average selling price for each product. average_price should
be rounded to 2 decimal places. Return the result table in any order.
The result format is in the following example.
Query MySQL
SELECT Prices.product_id,
IFNULL(ROUND(SUM(price * units)/SUM(units), 2), 0)
AS average_price
FROM Prices
LEFT JOIN UnitsSold ON Prices.product_id = UnitsSold.product_id
AND (UnitsSold.purchase_date BETWEEN start_date
AND end_date OR UnitsSold.purchase_date IS NULL)
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.
The query result format is in the following example.
Query MySQL
SELECT Project.project_id,
ROUND(AVG(Employee.experience_years), 2)
AS average_years
FROM Project
LEFT JOIN Employee
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.
The result format is in the following example.
Query MySQL
SELECT contest_id,
ROUND(
(COUNT(DISTINCT user_id) * 100 /
(SELECT COUNT(DISTINCT user_id)
FROM Users))
, 2) AS percentage
FROM Register
GROUP BY contest_id
ORDER BY percentage DESC, contest_id
Queries Quality and Percentage
Pertanyaan
We define query quality as$
+ The average of the ratio between query rating and its position.
We also define poor query percentage as$
+ The percentage of all queries with rating less than 3.
Write a solution to find each query_name, the quality and poor_query_percentage.
Both quality and poor_query_percentage should be rounded to 2 decimal places.
Return the result table in any order. The result format is in the following example.
Query MySQL
SELECT query_name,
ROUND(AVG(rating / position), 2) AS quality,
ROUND(AVG(rating < 3) * 100, 2) AS poor_query_percentage
FROM Queries
WHERE query_name IS NOT NULL
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.
Return the result table in any order.
The query result format is in the following example.
Query MySQL
SELECT DATE_FORMAT(trans_date, '%Y-%m') AS month,
country,
COUNT(*) AS trans_count,
SUM(IF(state='approved', 1, 0)) AS approved_count,
SUM(amount) AS trans_total_amount,
SUM(IF(state='approved',amount,0)) AS approved_total_amount
FROM Transactions
GROUP BY month, country
Immediate Food Delivery II
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.
The result format is in the following example.
Query MySQL
SELECT ROUND(
AVG(order_date = customer_pref_delivery_date) * 100
, 2) AS immediate_percentage FROM Delivery
WHERE (customer_id, order_date) IN (
SELECT customer_id, MIN(order_date) AS first_order
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.
The result format is in the following example.
Query MySQL
SELECT ROUND(
COUNT(DISTINCT player_id) /
(SELECT COUNT(DISTINCT player_id)
FROM Activity)
, 2) AS fraction FROM Activity
WHERE (player_id, DATE_SUB(event_date, INTERVAL 1 DAY)) IN (
SELECT player_id, MIN(event_date) AS first_login
FROM Activity
GROUP BY player_id
)
4 Sorting
and
Grouping
Soal Level
/. Number of Unique Subjects Taught by Easy
Each Teacher
E. User Activity for the Past 30 Days I Easy
L. Product Sales Analysis III Medium
q. Classes More Than 5 Students Easy
. Find Followers Count Easy
. Biggest Single Number Easy
. Customers Who Bought All Products Medium
Number of Unique Subjects Taught by
Each Teacher
Pertanyaan
Write a solution to calculate the number of unique subjects each teacher teaches in the
university. Return the result table in any order.
The result format is shown in the following example.
Query MySQL
SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt
FROM Teacher
GROUP BY teacher_id
User Activity for the Past 30 Days I
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.
The result format is in the following example.
Query MySQL
SELECT activity_date AS day,
COUNT(DISTINCT user_id) AS active_users
FROM Activity
WHERE (activity_date > '2019-06-27'
AND activity_date <= '2019-07-27')
GROUP BY activity_date
Product Sales Analysis III
Pertanyaan
Write a solution to select the product id, year, quantity, and price for the first year of
every product sold.
Return the resulting table in any order.
The result format is in the following example.
Query MySQL
SELECT product_id, year AS first_year, quantity, price
FROM Sales
WHERE (product_id, year) IN (
SELECT product_id, MIN(year) AS first_sold
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.
Return the result table in any order.
The result format is in the following example.
Query MySQL
SELECT class FROM Courses
GROUP BY class HAVING COUNT(class) >= 5
Find Followers Count
Pertanyaan
Write a solution that will, for each user, return the number of followers.
Return the result table ordered by user_id in ascending order.
The result format is in the following example.
Query MySQL
SELECT user_id,
COUNT(follower_id) AS followers_count
FROM Followers
GROUP BY user_id
ORDER BY user_id ASC
Biggest Single Number
Pertanyaan
A single number is a number that appeared only once in the MyNumbers table.
Find the largest single number. If there is no single number, report null.
The result format is in the following example.
Query MySQL
SELECT IF(COUNT(num) = 1, num, NULL) AS num
FROM MyNumbers
GROUP BY num
ORDER BY num DESC
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.
Return the result table in any order.
The result format is in the following example.
Query MySQL
SELECT customer_id FROM Customer
GROUP BY customer_id HAVING
COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
5 Advanced
Select
and Joins
Soal Level
0/ The Number of Employees Which Report Easy
to Each Employee
D/ Primary Department for Each Employee Easy
H/ Triangle Judgement Easy
a/ Consecutive Numbers Medium
|/ Product Price at a Given Date Medium
/ Last Person to Fit in the Bus Medium
/ Count Salary Categories Medium
The Number of Employees Which
Report to Each Employee
Pertanyaan
For this problem, we will consider a manager an employee who has at least 1 other
employee reporting to them.
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.
Return the result table ordered by employee_id.
The result format is in the following example.
Query MySQL
SELECT E1.employee_id, E1.name, E2.reports_count, E2.average_age
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
WHERE primary_flag = 'Y' OR employee_id IN (
SELECT employee_id
FROM Employee
GROUP BY employee_id HAVING COUNT(employee_id) = 1
)
Triangle Judgement
Pertanyaan
Report for every three line segments whether they can form a triangle.
Return the result table in any order.
The result format is in the following example.
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.
Return the result table in any order.
The result format is in the following example.
Query MySQL
WITH cte AS (
SELECT num,
LEAD(num, 1) OVER() AS next_num,
LAG(num, 1) OVER() AS before_num
FROM Logs
SELECT DISTINCT num AS ConsecutiveNums
FROM cte
WHERE num = next_num AND num = before_num
Product Price at a Given Date
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.
The result format is in the following example.
Query MySQL
WITH cte AS (
SELECT product_id, new_price,
ROW_NUMBER() OVER(PARTITION BY product_id ORDER BY change_date DESC)
AS rowNum FROM Products
WHERE change_date <= '2019-08-16'
SELECT DISTINCT Products.product_id,
COALESCE(cte.new_price, 10) AS price
FROM Products
LEFT JOIN cte ON Products.product_id = cte.product_id
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.
The result format is in the following example.
Query MySQL
WITH cte AS (
SELECT person_name, turn,
SUM(weight) OVER(ORDER BY turn) AS total_weight
FROM Queue
SELECT person_name FROM cte
WHERE total_weight <= 1000
ORDER BY total_weight DESC
LIMIT 1
Count Salary Categories
Pertanyaan
Write a solution to calculate the number of bank accounts for each salary category. The
salary categories are
"Low Salary": All the salaries strictly less than $200005
"Average Salary": All the salaries in the inclusive range [$20000, $50000]5
"High Salary": All the salaries strictly greater than $50000.
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
SELECT 'Low Salary' AS category, COUNT(*) AS accounts_count
FROM Accounts
WHERE income < 20000
UNION ALL
SELECT 'Average Salary' AS category, COUNT(*) AS accounts_count
FROM Accounts
WHERE income BETWEEN 20000 AND 50000
UNION ALL
SELECT 'High Salary' AS category, COUNT(*) AS accounts_count
FROM Accounts
WHERE income > 50000;
5
Subqueries
Soal Level
& Employees Whose Manager Left the Easy
Company
/ Exchange Seats Medium
> Movie Rating Medium
V Restaurant Growth Medium
_ Who Has the Most Friends Medium
v Investments in 2016 Medium
Department Top Three Salaries Hard
Employees Whose Manager Left the
Company
Pertanyaan
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.
Return the result table ordered by employee_id.
The result format is in the following example.
Query MySQL
SELECT employee_id FROM Employees
WHERE manager_id NOT IN (
SELECT employee_id
FROM Employees
AND salary < 30000
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.
Return the result table ordered by id in ascending order.
The result format is in the following example.
Query MySQL
SELECT CASE
WHEN id = (SELECT MAX(id) FROM Seat) AND id % 2 = 1 THEN id
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.
The result format is in the following example.
Query MySQL
(SELECT name AS results FROM movieRating
INNER JOIN users USING(user_id)
GROUP BY user_id
ORDER BY COUNT(movie_id) DESC, name ASC
LIMIT 1)
UNION ALL
(SELECT title FROM movieRating
INNER JOIN movies USING(movie_id)
WHERE EXTRACT(YEAR_MONTH FROM created_at) = 202002
GROUP BY movie_id
ORDER BY AVG(rating) DESC, title ASC
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.
The result format is in the following example.
Query MySQL
WITH cte AS (
SELECT visited_on,
SUM(amount) OVER (ORDER BY visited_on
RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW) AS amount,
MIN(visited_on) OVER () AS first_date
FROM Customer
SELECT DISTINCT visited_on, amount,
ROUND(amount / 7, 2) AS average_amount
FROM cte
WHERE visited_on >= first_date + 6
ORDER BY visited_on;
Who Has the Most Friends
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.
The result format is in the following example.
Query MySQL
SELECT id, COUNT(*) AS num
FROM (
SELECT requester_id AS id FROM RequestAccepted
UNION ALL
SELECT accepter_id FROM RequestAccepted
) AS friend_count
GROUP BY id
ORDER BY num DESC
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).
Round tiv_2016 to two decimal places.
The result format is in the following example.
Query MySQL
SELECT ROUND(SUM(a.tiv_2016), 2) AS tiv_2016
FROM Insurance a
WHERE a.tiv_2015 IN (
SELECT b.tiv_2015 FROM Insurance b
WHERE b.pid != a.pid
AND (a.lat, a.lon) NOT IN (
SELECT c.lat, c.lon FROM Insurance c
WHERE c.pid != a.pid
);
Department Top Three Salaries
Pertanyaan
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.
Write a solution to find the employees who are high earners in each of the departments.
Return the result table in any order.
The result format is in the following example.
Query MySQL
WITH cte AS (
SELECT Department.name AS Department,
Employee.name AS Employee,
Employee.salary AS Salary,
DENSE_RANK() OVER(PARTITION BY Department.name ORDER BY Salary DESC)
AS salaryRank FROM Employee
INNER JOIN Department ON Employee.departmentId = Department.id
SELECT Department, Employee, Salary
FROM cte
WHERE salaryRank <= 3;
7 Advanced
String
Functions
Soal Level
( Fix Names in a Table Easy
; Patients With a Condition Easy
@ Delete Duplicate Emails Easy
O Second Highest Salary Medium
y Group Sold Products By The Date Easy
List the Products Ordered in a Period Easy
Find Users With Valid E-Mails Easy
Fix Names in a Table
Pertanyaan
Write a solution to fix the names so that only the first character is uppercase and the rest
are lowercase.
Return the result table ordered by user_id.
The result format is in the following example.
Query MySQL
SELECT user_id,
CONCAT(
UPPER(SUBSTRING(name, 1, 1)), LOWER(SUBSTRING(name, 2))
AS name FROM Users
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.
Return the result table in any order.
The result format is in the following example.
Query MySQL
SELECT * FROM Patients
WHERE conditions LIKE 'DIAB1%' OR conditions LIKE '% %DIAB1%'
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.
The result format is in the following example.
Query MySQL
DELETE P1
FROM person P1
INNER JOIN person P2 ON P1.email = P2.email AND P1.id > P2.id;
Second Highest Salary
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).
The result format is in the following example.
Query MySQL
SELECT MAX(salary) AS SecondHighestSalary
FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee)
Sold Products By The Date
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.
Return the result table ordered by sell_date.
The result format is in the following example.
Query MySQL
SELECT sell_date,
COUNT(DISTINCT product) AS num_sold,
GROUP_CONCAT(DISTINCT product) AS products
FROM Activities
GROUP BY sell_date
ORDER BY sell_date
List the Products Ordered in a Period
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.
The result format is in the following example.
Query MySQL
SELECT P.product_name,
SUM(O.unit) AS unit
FROM Products AS P
INNER JOIN Orders AS O ON P.product_id = O.product_id
WHERE O.order_date BETWEEN '2020-02-01' AND '2020-02-29'
GROUP BY P.product_name HAVING unit >= 100
Find Users With Valid E-Mails
Pertanyaan
Write a solution to find the users who have valid emails.
A valid e-mail has a prefix name and a domain where
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 letter3
The domain is '@leetcode.com'.
Return the result table in any order.
The result format is in the following example.
Query MySQL
select * from Users
where mail REGEXP '^[a-zA-Z]+[a-zA-Z-._0-9]*@leetcode[.]com' > 0
Selamat
Belajar.
https://github.com/dipintoo