0% found this document useful (0 votes)
68 views

SQL Leetcode Questions

Uploaded by

srishti Jaitly
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

SQL Leetcode Questions

Uploaded by

srishti Jaitly
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Mazher Khan - Senior Data Analyst (IITian)- 6 years of Experience

SQL Leetcode Questions - Most Asked


175. Combine two tables
Fetch FirstName,Lastname, City, State
Select
Person Address P.FirstName, P.LastName, A.City, A.State
PersonID AddressID FROM PERSON P
Firstname PersonID LEFT JOIN ADDRESS A
Last Name City ON P.PERSONID=A.PERSONID;
State

176. Second Highest Salary


Fetch 2nd Highest Salary
SELECT Salary from (
ID Salary SELECT E.*, DENSE_RANK() OVER
1 100 (ORDER BY SALARY DESC)
2 200 AS RANK_SALARY FROM EMPLOYEE) A
3 300 WHERE RANK_SALARY=2;

180. Consecutive Numbers


Find all numbers that appear at least 3 times consecutively

ID NUM
1 1
2 1 SELECT A.NUM FROM LOGS A
3 1 INNER JOIN LOGS B
4 2 ON A.ID=B.ID+1 AND A.NUM=B.NUM
5 1 INNER JOIN LOGS C
6 2 ON A.ID=B.ID+2 AND A.NUM=C.NUM;
7 2

181. Employees Earning > Managers

ID Name Salary Manager ID SELECT E.ID, E.NANME


1 Joe 70000 3 FROM EMPLOYEE E
2 Henry 80000 4 INNER JOIN EMPLOYEE M
3 Sam 60000 NULL ON E.MANAGERID=M.ID
4 Max 90000 NULL E.SALARY>M.SALARY;

182. Duplicate Emails


Find Duplicate Emails

ID Email SELECT EMAIL


1 [email protected] FROM PERSON
2 [email protected] GROUP BY MAIL
3 [email protected] HAVING COUNT(*)>1
183. Customer who never order

Customers Orders SELECT NAME


ID ID FROM CUSTOMERS C
Name Customer ID LEFT JOIN ORDERS O
ON C.ID=O.ID
WHERE O.ID IS NULL;

184. Department Highest Salary

Id Name Salary DeptID WITH TABLE1 AS (


1 Joe 70000 1 Select E.*, DENSE_RANK()
2 Jim 90000 1 OVER (PARTITION BY DEPTID
ORDER BY SALARY DESC)
AS RANK_SALARY_DEPT
FROM EMPLOYEE E)
SELECT DEPTID, SALARY FROM TABLE1
WHERE RANK_SALARY_DEPT=1;

262. Trips and Users


Trips:
Id Client_Id Driver_Id City_Id Status Request_at
1 1 10 1 completed2013-10-01
2 2 11 1 cancelled_by_driver
2013-10-01
3 3 12 6 completed2013-10-01
4 4 13 6 cancelled_by_client
2013-10-01
5 1 10 1 completed2013-10-02

Users:
Users_Id Banned Role
1 No client
2 Yes client
3 No Driver
4 No client

Objective:
Find cancellation rate (unbanned users) between '2013-10-01' and '2013-10-03'
with X as (
Selec Request_at,Status from trip
where Request_at between '2013-10-01' and '2013-10-03'
and client_id not in (select user_id from users where banned='Yes')
and driver_id not in (select user_id from users where banned='Yes') )

SELECT Request_at,
ROUND(SUM(CANCELLED_FLAG)/SUM(COMPLETED_FLAG),2) AS CANCELLATION_RATE
SELECT X.*,
CASE WHEN Status='Completed' then 1
ELSE 0 END AS COMPLETED_FLAG,
CASE WHEN Status!='Completed' then 1
ELSE 0 END AS CANCELLED_FLAG FROM X;
512. Game Play Analysis II
Reports the device that is first logged in for each player.

player_id device_id event_date games_played


1 2 2016-03-01 5
1 2 2016-05-02 6
2 3 2017-06-25 1

SOLUTION-1
WITH MIN_PLAYER_DATE AS(
SELECT PLAYER_ID, MIN(EVENT_DATE) AS MIN_DATE
FROM ACTIVITY) SOLUTION-2
SELECT PLAYER_ID, DEVICE_ID
SELECT PLAYER_ID, DEVICE_ID FROM ACTIVITY
FROM ACTIVITY A WHERE (PLAYER_ID, EVENT_DATE)
INNER JOIN MIN_PLAYER_DATE M IN (SELECT PLAYER_ID, MIN(EVENT_DATE)
ON A.PLAYER_ID=M.PLAYER_ID FROM ACTIVITY
AND A.EVENT_DATE=M.EVENT_DATE GROUP BY PLAYER_ID);

534. Game Play Analysis III SELECT A.*,


Games played till date by PLAYER and DATE SUM(GAMES_PLAYED) OVER
(PARTITION BY PLYER_ID ORDR
player_id device_id event_date games_played BY EVENT_DATE)
1 2 2016-03-01 5 AS RUNNING_TOTAL_GAME
1 2 2016-05-02 6 FROM ACTIVITY A;

550. Game Play Analysis IV


Reports the fraction of players that logged in again on the day after the day they first logged in

player_id device_id event_date games_played


1 2 2016-03-01 5
1 2 2016-05-02 6

SELECT ROUND(COUNT(DISTINCT b.player_id)


/COUNT(DISTINCT a.player_id),2) AS fraction
FROM
(SELECT player_id, MIN(event_date) AS event_date
FROM Activity
GROUP BY player_id) a
LEFT JOIN Activity b
ON a.player_id = b.player_id
AND a.event_date+1 = b.event_date;
570. Managers with at Least 5 Direct Reports
SELECT NAME, EMPLOYEE
Id Name Department ManagerId FROM EMPLOYEE
101 John A null WHERE ID IN (
SELECT MANAGERID
FROM EMPLOYEE
GROUP BY MANAGERID
HAVING COUNT(DISTINCT ID)>=5);

579. Find Cumulative Salary of an Employee

Id Month Salary WITH X AS (


1 4 60 SELECT * FROM EMPLOYEES
1 3 40 WHERE (ID, MONHT) NOT IN
1 2 30 (SELECT ID, MAX(MONTH)
1 1 20 FROM EMPLOYEES
2 2 30 GROUP BY ID))
2 1 20
3 4 70 SELECT X.*,
3 3 60 SUM(SALARY) OVER
3 2 40 (PARTITION BY ID ORDER BY MONTH)
AS CUM_SALARY FROM X
ORDER BY MONTH;

586. Customer Placing the Largest Number of Orders

Order_ID SELECT
Customer_ID CUSTOMER_ID, COUNT(ORDER_ID)
FROM TABLE
GROUP BY CUSTOMER_ID
ORDER BY COUNT(ORDER_ID) DESC
LIMIT 1,1;

607.Sales Person
the names in the table salesperson, who didn’t have sales to company ‘RED’

SELECT name
FROM salesperson
WHERE name NOT IN
(SELECT DISTINCT salesperson.name
FROM salesperson, orders, company
WHERE company.name = 'RED'
AND salesperson.sales_id = orders.sales_id
AND orders.com_id = company.com_id)
619. Biggest Single Number
find the biggest number, which only appears once.

NUM
8 SELECT NUM
8 FROM X
3 GROUP BY NUM
3 HAVING COUNT(NUM)=1
1 ORDER BY NUM DESC LIMIT 0,1;
4
5
6

1045. Customers Who Bought All Products

Customer
Customer_ID SELECT CUSTOMER_ID
Product_Key FROM CUSTOMER
HAVING COUNT(DISTINCT PRODUCT_KEY)=
Product (SELECT DISTINCT COUNT PRODUCT_KEY
Product_Key FROM PRODUCT)

1070. Product Sales Analysis III


SELECT
Sales Product product_id, year first_year,
Sale_ID Product_ID quantity,price
Product_ID Product_Name FROM Sales
Year WHERE (product_id, year)
QTY IN (SELECT product_id, MIN(year)
PRICE FROM Sales
GROUP BY product_id)

1098. Unpopular Books


reports the books that have sold SELECT
less than 10 copies in the last year b.book_id, b.name
, excluding books that have been FROM Books b LEFT JOIN (
available for less than 1 month from SELECT book_id, SUM(quantity)
today. Assume today is 2019-06-23 nsold FROM Orders
WHERE dispatch_date BETWEEN
Books Orders '2018-06-23' AND '2019-06-23'
Book_ID Order_ID GROUP BY book_id) o
Name Book_ID ON b.book_id = o.book_id
Available_from Qty WHERE
Disptach_date (o.nsold < 10 OR o.nsold IS NULL) AND
DATEDIFF('2019-06-23', b.available_from) > 30
1126. Active Businesses
Find all active businesses that has more than one event type and
occurences greater than the average occurences of that event type among all businesses

business_id event_type occurences WITH X AS (


1 reviews 7 SELECT DISTINCT BUSINESS_ID
3 reviews 3 FROM TABLE
1 ads 11 GROUP BY EVENT_TYPE)
2 ads 7 HAVING COUNT(DISTINCT EVNT_TYPE)>1,
3 ads 6 Y AS (
1 page views 3 SELECT EVENT_TYPE, AVG(OCCURENCES)
FROM TABLE
GROUP BY EVENT_TYPE)

SELECT * FROM TABLE


LEFT JOIN Y
ON TABLE.EVENT_TYPE=Y.EVENT_TYPE
AND OCCURENCES>AVG(OCCURENCES)
WHERE BUSINESS_ID=
(SELECT * FROM X)

1132. Reported Posts II


Average for daily percentage of posts that got removed after being reported as spam

Actions Removals
USER_ID POST_ID WITH X AS (
POST_ID REMOVE_DATE SELECT ACTION_DATE,REPORTED_POST_ID,
ACTION_DATE REMOVED_POST_ID FROM (
ACTION SELECT A.*, R.POST_ID FROM ACTIONS A
EXTRA LEFT JOIN REMOVALS R
ON A.POST_ID=R.POST_ID)
WHERE ACTION='REPORT'
AND EXTRA = 'SPAM')

SELECT ACTION_DATE,
ROUND(COUNT (REPORTED_POST_ID)/
COUNT(REMOVED_POST_ID),2)
FROM X

1179. Reformat Department Table


SELECT id,
Department SUM(IF(month='Jan', revenue, NULL))
ID AS Jan_Revenue,
REVENUE SUM(IF(month='Feb', revenue, NULL))
MONTH AS Feb_Revenue
FROM Department
id | Jan_Revenue | Feb_Revenue etc. Group BY id;
1193. Monthly Transactions I
DATE_FORMAT(trans_date,'%Y-%m')

1270. All People Report to the Given Manage


Employees that directly or indirectly (<=3 Managers) report their work to the head of company

employee_id employee_namemanager_id SELECT t1.employee_id


1 Boss 1 FROM Employees AS t1
3 Alice 3 INNER JOIN Employees AS t2
2 Bob 1 ON t1.manager_id = t2.employee_id
4 Daniel 2 JOIN Employees AS t3
7 Luis 4 ON t2.manager_id = t3.employee_id
8 Jhon 3 WHERE t3.manager_id = 1
9 Angela 8 AND t1.employee_id != 1
77 Robert 1

1321. Restaurant Growth


Input
customer_id name visited_on amount
1 Jhon 1/1/2019 100
2 Daniel 1/2/2019 110
3 Jade 1/3/2019 120
4 Khaled 1/4/2019 130

Output SELECT visited_on, SUM(amount)


visited_on Amount Avg_Amount R6W OVER(ORDER BY visited_on ROWS 6
1/7/2019 860 122.86 PRECEDING),
1/8/2019 840 120.00 round(avg(amount) OVER(ORDER BY
1/9/2019 840 120.00 visited_on
1/10/2019 1000 142.86 ROWS 6 PRECEDING),2) FROM (
SELECT visited_on, SUM(amount)
amount
FROM customer
GROUP BY visited_on
ORDER BY visited_on
)a
ORDER BY visited_on offset 6 ROWS

1327. List the Products Ordered in a Period


Products >=100 units in Feb '20 SELECT P.PRODUCT_NAME, SUM(UNITS) UNIT_All
FROM PRODUCTS P
Products Orders INNER JOIN ORDERS O
Product_id Product_id ON P.PRODUCT_ID=O.PRODUCT_ID
Product_name Order_date WHERE MONTH='FEB'
Product_category unit GROUP BY P.PRODUCT_NAME
HAVING SUM(UNITS)>=100;
1336. Number of Transactions per Visit

Visits Transactions WITH X AS (


user_id user_id SELECT USER_ID, TRANSACTION_DATE,
visit_date transaction_date COUNT(USER_ID) AS COUNT_USERS
amount FROM TRANSACTIONS
GROUP BY USER_ID, TRANSACTION_DATE)

SELECT transactions_count,
SUM(transactions_count) AS visits_count
FROM (
SELECT IFNULL(X.COUNT_USERS,0)
AS transactions_count
FROM USERS U
LEFT JOIN X
ON U.USER_ID=X.USER_ID
AND U.VISIT_DATE=X.TRANSACTION_DATE)
GROUP BY transactions_count;

1341. Movie Rating


User who has rated the greatest number of the movies.
movie name with the highest average rating in February 2020

Movies Users Movie_Rating


movie_id user_id movie_id
title name user_id
rating
created_at

WITH X AS ( SELECT NAME,COUNT(USER_ID) RTD_MOV_CNT


SELECT * FROM MOVIE_RATING R AS FROM X
INNER JOIN MOVIES M >>>>>> GROUP BY NAME
ON R.MOVIED_ID=M.MOVIED_ID ORDER BY COUNT(USER_ID), NAME LIMIT 0,1
INNER JOIN USERS U UNION ALL
ON R.USER_ID=U.USER_ID) SELECT TITLE,AVG(RATING) AVG_RATING
AS FROM X
GROUP BY TITLE
ORDER BY AVG(RATING), TITLE LIMIT 0,1
1412. Find the Quiet Students in All Exams
A “quite” student is the one who took at least one exam and
didn’t score neither the high score nor the low score.
Report Quiet Student
With max_score as (
Student Exams SELECT max(score) from exams),
student_id exam_id min_score as (
student_name student_id SELECT min(score) from exams),
score exam_taken as (
Select student_id, count(student_id) exam_count
from exams
group by exams)

Select Student_Id from (


SELECT * from Exams
left join exam_taken
on exams.student_id=exam_taken.student_id
where exam_taken.exam_count>0
AND Score not in =max_score or
Score not in = min_score );

1454. Active Users


Find Active Users who logged in to their accounts for 5 or more consecutive days.

Logins WITH T1 AS (
ID SELECT A.*,
Login_Date LEAD(LOGIN_DATE,4) OVER
(PARTITION BY ID ORDER BY LOGIN_DATE) DATE_5
FROM (SELECT DISTINCT * FROM LOGINS) A)

SELECT ID FROM T1
WHERE DATEDIFF(DATE_5, LOGIN_DATE)=4

1484. Group Sold Products By The Date


For each date, the number of distinct products sold and their names

Activities Sell_Date Num_Sold Products


Sell_date 5/30/2020 3 Basketball,Headphone,T-shirt
Product 6/1/2020 2 Bible,Pencil
6/2/2020 1 Mask

SELECT sell_date, COUNT(DISTINCT product) AS num_sold,


group_concat(DISTINCT product) AS products
FROM activities GROUP BY 1
1501. Countries You Can Safely Invest In
Countries where this company can invest

PERSON COUNTRY CALLS


ID NAME CALLEE_ID
NAME COUNTRY_CODECALLER_ID
PHONE_NUM DURATION

WITH T1 AS (
SELECT ID, SUM(CALLS) CALLS FROM( SELECT COUNTRY.NAME, AVG(CALLS)
SELECT DISTINCT CALLEE_ID ID, AS COUNTRY_AVG_CALLS FROM (
DURATION FROM CALLS SELECT T1.CALLS, COUNTRY.NAME FROM T1
UNION ALL >>>>>>> INNER JOIN PERSON
SELECT DISTINCT CALLER_ID ID, T1.ID=PERSON.ID
DURATION FROM CALLS) INNER JOIN COUNTRY
GROUP BY ID ON LEFT(PERSON.PHONE_NUM,3)=COUNTRY.COUNTRY_CODE)
), HAVING AVG(CALLS)>=AVG_NTN_CALLS;
AVG_NTN_CALLS AS (
SELECT AVG(CALLS) FROM T1),

1517. Find Users With Valid E-Mails

#Solution 1:
SELECT user_id, name, mail
FROM Users
WHERE mail regexp "^[a-zA-Z]+[a-zA-Z0-9_\./\-]{0,}@leetcode\.com$"
ORDER BY user_id

#Solution 2:
SELECT * FROM Users
WHERE regexp_like(mail, '^[A-Za-z]+[A-Za-z0-9_.-]*@leetcode.com')
(mail, '^[A-Za-z]+[A-Za-z0-9_.-]*@leetcode.com')

1532. The Most Recent Three Orders

CUSTOMERS WITH tmp AS (


CUSTOMER_ID SELECT a.name, a.customer_id, b.order_id, b.order_date,
NAME ROW_NUMBER() OVER(PARTITION BY a.name, a.customer_id
ORDER BY b.order_date DESC) AS rnk
FROM Customers AS a
JOIN Orders AS b
ORDERS ON a.customer_id = b.customer_id
ORDER_ID )
ORDER_DATE
CUSTOMER_ID SELECT name AS customer_name, customer_id, order_id,
COST order_date FROM tmp WHERE rnk <= 3
ORDER BY customer_name, customer_id, order_date DESC;
1549. The Most Recent Orders for Each Product

ORDER PRODUCTS
order_id product_id SELECT p.product_name, o.product_id, o.order_id,
order_date product_name o.order_date FROM(
customer_id price SELECT product_id, order_id, order_date,
product_id RANK() OVER(PARTITION BY product_id
ORDER BY order_date DESC) AS seq
FROM orders ) o LEFT JOIN products p
ON o.product_id = p.product_id
WHERE o.seq = 1 ORDER BY 1,2,3

1555. Bank Account Summary


Query to report user_id, name, current credit balance, breached (Y/N)

Users TRANSACTIONS WITH DEBIT AS (


user_id trans_id SELECT U.*, (T.AMOUNT)*-1 AS DEBIT
user_name paid_by FROM USERS U
credit_balance paid_to INNER JOIN TRANSACTIONS T
amount ON U.USER_ID=T.PAID_BY),
transacted_on MASTER AS (
SELECT D.*, (T.AMOUNT) AS CREDIT
FROM DEBIT D
INNER JOIN TRANSACTIONS T
ON D.USER_ID=T.PAID_TO
)

SELECT USER_ID, USER_NAME,


sum(CREDIT_BALANCE,CREDIT,DEBIT) AS CCB
FROM MASTER;

1613. Find the Missing IDs


Input Output WITH RECURSIVE CTE AS(
Customer Customer SELECT 1 AS 'id', MAX(c.customer_id) AS 'Max_Id'
1 2 FROM Customers c
4 3 UNION ALL
5 SELECT id+1, Max_Id ROM CTE
WHERE id < Max_id )

SELECT id AS 'ids'
FROM CTE c
WHERE c.id NOT IN
(SELECT customer_id FROM Customers)
ORDER BY 1 ASC
M,3)=COUNTRY.COUNTRY_CODE)

You might also like