1174. Immediate Food Delivery II | Medium | ( LeetCode
Table: velivery
| delivery_id [ant |
| customer_id | int |
| order_date | date |
| custoner_pref_delivery date | date |
delivery_id is the primary key of this table.
The table holds information about food delivery to customers that make orders at
a
If the preferred delivery date of the customer is the same as the order date then the
order is called immediate otherwise it’s called scheduled.
The first order of a customer is the order with the earliest order date that customer
made. It is guaranteed that a customer has exactly one first order.
Write an SQL query to find the percentage of immediate orders in the first orders of
all customers, rounded to 2 decimal places.
The query result format is in the following example:
Delivery table:
delivery_id | customer_id | order_date | customer_pref_delivery date |
Ja Ja | 2019-08-01 | 2019-08-02 |
[2 12 | 2¢19-8-02 | 2019-08-22 Il
13 Ja | 2019-08-11 | 2019-08-12 |
l4 13 | 2019-08-24 | 2019-@8-24 Il
Is 13 | 2019-08-21 | 2019-08-22 |
16 12 | 2@19-@8-11 | 2019-08-13 |7 [4 | 2019-08-09 | 2019-08-09
Result table:
| immediate_percentage |
The customer id 1 has a first order with delivery id 1 and it is scheduled.
The customer id 2 has a first order with delivery id 2 and it is immediate.
The customer id 3 has a first order with delivery id 5 and it is scheduled.
The customer id 4 has a first order with delivery id 7 and it is immediate.
Hence, half the customers have immediate first orders.
Solution
SELECT ROUND(SUM(CASE WHEN order_date=custoner_pref_delivery date THEN 1 ELSE @ E
FROM Delivery
WHERE (customer_id, order_date) IN
(SELECT customer_id, MIN(order_date)
FROM Delivery
GROUP BY customer
id)
SELECT ROUND(AVG(CASE WHEN order_date = customer_pref_delivery date THEN 1 ELSE @
inmediate_percentage
FROM
(SELECT *,
RANK() OVER(PARTITION BY customer_id ORDER BY order_date) AS rk
FROM delivery) a
WHERE a.rk=1
1179. Reformat Department Table | Easy | LeetCodeTable: Department
| column Name | Type |
| ad [int |
| revenue | int |
| month | varchar |
(id, month) is the primary key of this table.
The table has information about the revenue of each department per month.
"sul", "aug",
Mar”, "Apr
The month has values in ["Jan"
——TT—
Write an SQL query to reformat the table such that there is a department id column
and a revenue column for each month.
The query result format is in the following example:
Department table:
| id | revenue | month |
}1 | 8000 © | gan |
[12 | 900@ | Jan |
13 | 10000 | Feb |
[1 | 7000 | Feb |
}1 | 6000 © | Mar |
| id | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |
| 8000 | 7e00 | 6000
1 null \
2 | 9000 | nul | nui
3
null \
null, |
| null | 1¢¢00 | mulaNote that the result table has 13 colunns (1 for the department id + 12 for the m
Solution
SELECT id,
SUM(IF(mont revenue,
SUM(IF (mont revenue,
SUM(IF(month='Mar’, revenue,
SUM(IF(month='Apr', revenue,
SUM(TF (mont revenue,
SUM(IF (mont revenue,
SUM(IF(month="Aug’, revenue,
SUM( IF (mont!
SUM(TF (mont!
SUM(IF(mont
‘SUM( TF (mont!
Sep’, revenue,
Oct", revenue,
Nov’, revenue,
"Dec', revenue,
FROM Department
Group BY id;
1193. Monthly Transactions I | Medium | ( LeetCode
Table: Transactions
| column Name | Type |
| ad [int |
| country | varchar |
| state | enum |
| amount, | int |
NULL))
NULL))
NULL))
NULL))
NULL))
NULL))
NULL))
NULL))
NULL))
NULL))
NULL))
NULL))
Jan_Revenue,
Feb_Revenue,
Mar_Revenue,
Apr_Revenue,
May_Revenue,
3un_Revenue,
dul_Revenue,
‘Aug_Revenue,
Sep_Revenue,
oct_Revenue,
Nov_Revenue,
Dec_Revenue
=| transdate | date |
id is the primary key of this table.
The table has information about incoming transactions.
The state column is an enum of type ["approved", “declined"].
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.
The query result format is in the following example:
Transactions table:
| id | country | state | amount | trans_date |
| 12a | us | approved | 1000 | 2018-12-18 |
| 122 | us | declined | 2000 | 2018-12-29 |
| 123, | us | approved | 2000 | 2019-01-01 |
| 124 | oe | approved | 2000 | 2019-01-07 |
| month — | country | trans_count | approved_count | trans_total_amount | approv
| 2e18-12 | us 12 fa | 3e00 | 1000
| 219-01 | us Ja ja | 2000 | 2000
| 2e19-e1 | bE fa fa | 2600 | 2000
Solution
WITH t2 AS(
SELECT DATE_FORMAT(trans_date, 'RY-%m') AS month, country, COUNT(state) AS trans_cFROM transactions
GROUP BY country, month(trans_date)),
t2 AS (
SELECT DATE_FORMAT(trans_date, 'XY-%m') AS month, country, COUNT(state) AS approve
FROM transactions
WHERE state = ‘approved"
GROUP BY country, month(trans_date))
SELECT t1.month, t1.country, COALESCE(t1.trans_count,@) AS trans_count, COALESCE(
FROM 1 LEFT JOIN t2
ON t2.country = t2.country and t1.month = t2.month
1194, Tournament Winners | Hard | i LeetCode
Table: Players
| Column Name | Type |
| playerid | int |
| group_id | int |
player_id is the primary key of this table.
Each row of this table indicates the group of each player.
Table: Matches
| Column Name | Type =|
int |
| match_id |
| first_player | int = |
|
| second_player | int || first_score | int = |
| second_score | int |
match_id is the primary key of this table.
Each row is a record of a match, first_player and second_player contain the playe
first_score and second_score contain the number of points of the first_player and
You may assume that, in each match, players belongs to the same group.
—
The winner in each group is the player who scored the maximum total points within
the group. In the case of a tie, the lowest player_id wins.
Write an SQL query to find the winner in each group.
The query result format is in the following example:
Players table:
| player_id | groupid |
Matches table:
| match_id | first_player | second_player | first_score | second_score |
| 15 | 45 |
|
|
fa 13 le
|2 | 30 | 25 ja [2
13 | 30 | as [2 le| group_id | playerid |
| a5 |
35 |
| 40 |
ja
[2 |
13
WITH £1 AS(
SELECT first_player, SUM(first_score) AS total
FROM
(SELECT first_player, first_score
FROM matches
UNION ALL
SELECT second_player, second_score
FROM matches) a
GRouP BY 2),
£2 As(
SELECT *, COALESCE(total,®) AS score
FROM players p LEFT JOIN ti
ON p.player_id = t1.first_player)
SELECT group_id, player_id
FROM,
(SELECT *, ROW_NUMBER() OVER(PARTITION BY group_id ORDER BY group_id, score DESC)
FROM £2) b
WHERE barn = 11204. Last Person to Fi
in the Elevator | Medium | (j LeetCode
Table: queue
personid | int = |
person_nane | varchar |
weight [aint |
turn | int |
person_id is the primary key colunn for this table.
This table has the information about all people waiting for an elevator.
The person_id and turn columns will contain all numbers from 1 ton, where n is t
—
The maximum weight the elevator can hold is 1000.
Write an SQL query to find the person_name of the last person who will fit in the
elevator without exceeding the weight limit. It is guaranteed that the person who is
first in the queue can fit in the elevator.
The query result format is in the following example:
Queue table
| person_id | person_name | weight | turn |
Is | George Washington | 250 | 1 |
13 | John Adams |3se |2 |
le | Thomas Jefferson | 400 | 3 |
[2 | Will Johnliams | 200 =| 4 |
la | Thomas Jefferson | 175 | 5 |
fa | James Elephant | 50@ | 6 |Result table
| person_name |
| Thomas Jefferson |
Queue table is ordered by turn in the example for simplicity.
In the example George Washington(id 5), John Adams(id 3) and Thomas Jefferson(id
Thomas Jefferson(id 6) is the last person to fit in the elevator because he has t
—S —
Solution
WITH t1 aS
(
SELECT *,
SUM(weight) OVER(ORDER BY turn) AS cum_weight
FROM queue
ORDER BY turn)
SELECT t1.person_name
FROM t1
WHERE turn = (SELECT MAX(turn) FROM ti WHERE t1.cum_weight<=1000)
1205. Monthly Transactions II | Medium | ( LeetCode
Table: Transactions
| column Name | Type |
| ad [aint |
| country | varchar || state | enum |
| amount | int |
| transdate | date |
id is the primary key of this table.
The table has information about incoming transactions.
The state column is an enun of type ["approved", “declined"].
Table: chargebacks
| Column Name | Type |
| trans_id | int |
| chargedate | date |
Chargebacks contains basic information regarding incoming chargebacks from some t
trans_id is a foreign key to the id column of Transactions table.
Each chargeback corresponds to a transaction made previously even if they were no
—
Write an SQL query to find for each month and country, the number of approved
transactions and their total amount, the number of chargebacks and their total
amount.
Note: In your query, given the month and country, ignore rows with all zeros.
The query result format is in the following example:
Transactions table:
| id | country | state | amount | trans_date |
| ae1 | us | approved | 1000 | 2019-05-28 |
| 102 | us | declined | 2000 | 2019-05-19 |
| 1e3 | us | approved | 3000 | 2019-06-10 || 184 | us | approved | 4000 | 2019-06-13 |
[aes | us | approved | seee | 2019-06-15 |
Chargebacks table:
| trans_id | trans_date |
| 102 | 2019-05-29 |
| 101 | 2019-06-3@ |
| 105 | 2019-09-18 |
Result table:
| month | country | approved_count | approved_amount | chargeback_count | cha
| 2e19-e5 | us fa | 1000 fa | 206
| 2019-06 | us 13 | 12000 [a | 108
| 2e19-e9 | us le le fa | see
Solution
WITH ta aS
(SELECT country, extract('month’ FROM trans_date), state, COUNT(*) AS approved_co
FROM transactions
WHERE state = ‘approved"
GROUP BY 1, 2, 3),
£2 As(
SELECT t.country, extract("month’ FROM c.trans_date), SUM(amount) AS chargeback_a
FROM chargebacks c LEFT JOIN transactions t
ON trans_id = id
GROUP BY t.country, extract('month’ FROM c.trans_date)),£3 AS(
SELECT t2.date_part, t2.country, COALESCE (approved_count,@) AS approved_count, CO
FROM t2 LEFT JOIN ti
ON t2.date_part = ti.date_part AND t2.country = ti.country),
ta As(
SELECT ti.date_part, t1.country, COALESCE(approved_count,@) AS approved_count, CO
FROM t2 RIGHT JOIN ti
ON t2.date_part = ti.date_part AND t2.country = t1.country)
SELECT *
FROM t3
UNTON
SELECT *
FROM t4
SELECT month, country,
‘SUM(CASE WHEN type='approved' THEN 1 ELSE @ END) AS approved_count,
SUM(CASE WHEN type=' approved" THEN amount ELSE @ END) AS approved_amount,
SUM(CASE WHEN type='chargeback" THEN 1 ELSE @ END) AS chargeback_count,
SUM(CASE WHEN type='chargeback’ THEN amount ELSE @ END) AS chargeback_anount
FROM (
(
SELECT left(t.trans_date, 7) AS month, t.country, amount, ‘approved’ AS type
FROM Transactions AS t
WHERE state=" approved"
)
UNEON ALL (
SELECT left(c.trans_date, 7) AS month, t.country, amount, "chargeback" AS type
FROM Transactions AS t JOIN Chargebacks AS
ON t.id = c.trans_id
)
yas tt
GROUP BY tt.month, tt.country
SELECT month, country,
SUM(CASE WHEN typ
SUM(CASE WHEN typ
approved’ THEN count ELSE @ END) AS approved_count,
approved’ THEN amount ELSE @ END) AS approved_amount,SUM(CASE WHEN typ
SUM(CASE WHEN typ
FROM (
(
SELECT LEFT(t.trans_date, 7) AS month, t.country,
COUNT(1) AS count, SUM(amount) AS amount, ‘approved’ AS type
FROM Transactions AS t LEFT JOIN Chargebacks AS c
chargeback’ THEN count ELSE @ END) AS chargeback_count,
chargeback’ THEN amount ELSE @ END) AS chargeback_anount
ON t.id = ¢.trans_id
WHERE state=' approved"
GROUP BY LEFT(t.trans_date, 7), t.country
)
union (
SELECT LEFT(c.trans_date, 7) AS month, t.country,
COUNT(1) AS count, SUM(amount) AS amount, ‘chargeback’ AS type
FROM Transactions AS t JOIN Chargebacks AS c
ON t.id = ¢.trans_id
GROUP BY LEFT(c.trans_date, 7), t.country
)
) AS tt
GROUP BY tt.month, tt.country
1211. Queries Quality and Percentage | Easy | (@ LeetCode
Table: queries
| Column Name | Type |
| query_name | varchar |
| result | varchar |
| position | int = |
| rating | int |
There is no primary key for this table, it may have duplicate rows.
This table contains information collected from some queries on a database.The position column has a value from 1 to 500.
‘The rating column has a value from 1 to 5. Query with rating less than 3 is a poo
=—
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 an SQL query to find each query_name, the quality and poor_query_percentage.
Both quality and poor_query_percentage should be rounded to 2 decimal places.
The query result format is in the following example:
Queries table:
| query_name | result | position | rating |
| dog | Golden Retriever | 1 15 |
| bog | German shepherd | 2 is |
| dog | mute | 200 [a I
| cat | shirazi Is 12 I
| cat | Siamese 13 13 |
| cat | sphynx 17 la I
Result table:
| query_nane | quality | poor_query_percentage |
| dog. | 2.50 | 33.33 |
| cat |.66 | 33.33 |Dog queries quality is ((5 / 1) + (5 / 2) + (1 / 200)) / 3 = 2.50
Dog queries poor_ query_percentage is (1 / 3) * 10@ = 33.33
Cat queries quality equals ((2 / 5) + (3 / 3) + (4/ 7)) / 3 = 0.66
Cat queries poor_ query_percentage is (1 / 3) * 100 = 33.33
.
SELECT query_name, ROUND(SUM(rating/position)/COUNT(*),2) AS quality,
ROUND(AVG(CASE WHEN rating<3 THEN 1 ELSE @ END)*100,2) AS poor_query_percentage
FROM queries
GROUP BY query_name
SELECT query_name, ROUND(AVG(rating/position), 2) AS quality,
ROUND(100*SUM(CASE WHEN rating<3 THEN 1 ELSE @ END)/COUNT(1), 2) AS poor_q
FROM Queries
GROUP BY query_name
1212. Team Score:
LeetCode
Football Tournament | Medium | @®
Table: Teams
| Column Name | Type |
| team_id | int |
| teamname | varchar |
‘team_id is the primary key of this table.
Each row of this table represents a single football team.Table: matches
| column Name | Type |
| match_id [int |
| host_team | int |
| guest_tean | int =|
| host_goals | int |
| guest_goals | int =|
match_id is the primary key of this table.
Each row is a record of a finished match between two different teams.
Teams host_team and guest_team are represented by their IDs in the teams table (t
—_—_—,
You would like to compute the scores of all teams after all matches. Points are
awarded as follows:
+ A team receives three points if they win a match (Score strictly more goals than
the opponent team).
+ A team receives one point if they draw a match (Same number of goals as the
opponent team).
* Ateam receives no points if they lose a match (Score less goals than the
opponent team).
Write an SQL query that selects the teamid, teamname and numpoints of each
team in the tournament after all described matches. Result table should be
ordered by numpoints (decreasing order). In case of a tie, order the records by
team_id (increasing order)
The query result format is in the following example:
Teams table| teamid | team_name |
| 10 | Leetcode Fe |
| 26 | NewYork FC |
| 30 | atlanta Fc |
| 40 | chicago FC |
| 50 | Toronto FC |
Matches table:
| match_id | host_team | guest_team | host_goals | guest_goals |
fa | 16 | 26 13 le |
12 | 30 | 10 l2 |2 |
13 | 18 | se Is fa |
[4 | 20 | 3e ja le |
15 | se | 3e fa le |
| teamid | team_name | num_points |
| 10 | Leetcode FC | 7 |
| 26 | Newyork FC | 3 |
| 50 | Toronto FC | 3 |
| 30 | atlanta Fe | a |
| 40 | chicago FC | @ |
Solution
SELECT Teams.team_id, Teans.team_name,
jost_team AND host_goals>guest_goals THEN 3 ELSE @ END)
SUM(CASE WHEN team_ii
SUM(CASE WHEN team_i
jost_team AND host_goals=guest_goals THEN 1 ELSE @ END)SUM(CASE WHEN team_i
SUM(CASE WHEN team_i
FROM Teams LEFT JOIN Matches
uest_team AND host_goals
guest_goals THEN 3
WHEN host_goall
ELSE @ END) AS num_points
juest_goals THEN 1
FROM Matches
GROUP BY host_tean
UNION ALL
SELECT guest_team AS tean_id,
SUM(CASE WHEN host_goalsguest_goals THEN 3
WHEN host_goall
ELSE @ END) AS num_points
juest_goals THEN 1
FROM Matches
GROUP BY host_tean
UNION ALLSELECT guest_team AS tean_id,
SUM(CASE WHEN host_goals a.guest_goals THEN 3
WHEN a.host_goals = a.guest_goals THEN 1
ELSE @ END AS host_points,
CASE WHEN a.host_goals < a.guest_goals THEN 3
WHEN a.host_goals = a.guest_goals THEN 1
ELSE @ END AS guest_points
FROM(
SELECT *
FROM matches m
JOIN teams t
ON t.team_id = m.host_team) a
JOIN
(SELECT *
FROM matches m
JOIN teams t
ON t.team_id = m.guest_team) b
ON a.match_id = b.match_id) c
UNION ALL
SELECT d.guest_id, d.guest_name, d.guest_points
FROM(
SELECT a.match_id, a.team_id AS host_id, a.team_name AS host_name, b.team_id AS g
CASE WHEN a.host_goals > a.guest_goals THEN 3
WHEN a.host_goals = a.guest_goals THEN 1
ELSE @ END AS host_points,CASE WHEN a.host_goals < a.guest_goals THEN 3
WHEN a.host_goals = a.guest_goals THEN 1
ELSE @ END AS guest_points
FROM(
SELECT *
FROM matches m
JOIN teams t
ON t.team_id = m.host_team) a
JOIN
(SELECT *
FROM matches m
JOIN teams t
ON t.team_id = m.guest_team) b
ON a.match_id = b.match_id) d)
SELECT team_id, teamname, coalesce(total,®) AS num_points
FROM teams t2
LEFT J0IN(
SELECT host_id, host_nane, SUM(host_points) AS total
FROM t2
GROUP BY host_id, host_nane) e
ON t2.team_id = e.host_id
ORDER BY num_points DESC, team_id
1225. Report Contiguous Dates | Hard | (@ LeetCode
Table: Failed
| Column Name | Type |
| faildate | date |
Primary key for this table is fail_date.
Failed table contains the days of failed tasks.Table: succeeded
| column Name | Type |
| success date | date |
+e
Primary key for this table is success_date.
Succeeded table contains the days of succeeded tasks.
A system is running one task every day. Every task is independent of the previous
tasks. The tasks can fail or succeed.
Write an SQL query to generate a report of period_state for each continuous interval
of days in the period from 2019-01-01 to 2019-12-31.
periodstate is ‘failed’ if tasks in this interval failed or ‘succeeded’ if tasks in this
interval succeeded. Interval of days are retrieved as startdate and end_date.
Order result by start_date.
The query result format is in the following example:
Failed table
+e
| fail_date |
2018-12-28
2018-12-29
2019-01-04
2019-@1-05
bof
Succeeded table:
&
| success date2018-12-38
2018-12-31
2019-01-01
2019-01-02
2019-01-03
2019-01-06
Result table:
| period_state | start_date
| end_date |
| succeeded | 2019-01-01 | 2019-81-03 |
| failed | 2019-01-04 | 2019-01-05 |
| succeeded | 2019-01-06 | 2019-01-26 |
The report ignored the system state in 2018 as we care about the system in the pe
From 2019-01-01 to 2019-01-03 all tasks succeeded and the system state was “succe
From 2019-@1-04 to 2019-01-05 all tasks failed and system state was “failed”
From 2019-01-06 to 2019-01-06 all tasks succeeded and system state was “succeeded
—
Solution
WITH t1 ASC
SELECT MIN(success_date) AS start_date, MAX(success_date) AS end_date, state
FROM(
SELECT *, date_sub(success date, interval ROM_NUMBER() OVER(ORDER BY success_date
FROM succeeded
WHERE success_date BETWEEN "2019-01-01" AND "2019-12-31") a
GROUP BY diff),
£2 As(
SELECT MIN(fail_date) AS start_date, MAX(fail_date) AS end_date, stateFROM(
SELECT *, date_sub(fail_date, interval ROW_NUMBER() OVER(ORDER BY fail_date) day)
FROM failed
WHERE fail_date BETWEEN "2019-01-01" AND "2019-12-31") b
GROUP BY diff)
SELECT
CASE WHEN c.state = 1 THEN “succeeded”
ELSE “failed”
END AS period_state,start_date, end_date
FROM(
SELECT *
FROM t1.
UNION ALL
SELECT *
FROM £2) ¢
ORDER BY start_date
SELECT period_state, MIN(date) AS start_date, MAX(date) AS end_date
FROM (
SELECT period state, date,
@rank := CASE WHEN @prev = period state THEN @rank ELSE @rank+1 END AS r
@prev := period_state AS prev
FROM (
SELECT "failed’ AS period_state, fail_date AS date
FROM Failed
WHERE fail_date BETWEEN '2019-@1-01' AND '2019-12-31"unTON
SELECT ‘succeeded’ AS period state, success date AS date
FROM Succeeded
WHERE success date BETWEEN '2019-@1-@1' AND '2019-12-31') AS t,
(SELECT @rank:=@, prev
ORDER BY date ASC) AS tt
GROUP BY rank
ORDER BY rank
") AS rows
1241. Number of Comments per Post | Easy | (@) LeetCode
Table: submissions
| column Name | Type |
| sub_id | int |
| parent_id | int |
There is no primary key for this table, it may have duplicate rows.
Each row can be a post or comment on the post.
parent_id is null for posts.
parent_id for conments is sub_id for another post in the table.
Write an SQL query to find number of comments per each post.
Result table should contain post_id and its corresponding nunber_of_connents , and
must be sorted by post_id in ascending order.
Submissions may contain duplicate comments. You should count the number of
unique comments per post.
Submissions may contain duplicate posts. You should treat them as one post.
The query result format is in the following example:Submissions table:
| subid | parent_id |
The post with id 1 has three comments in the table with id 3, 4 and 9. The commen
The post with id 2 has two comments in the table with id 5 and 10.
The post with id 12 has no comments in the table.
The comment with id 6 is a comment on a deleted post with id 7 so we ignored it.
—_—_—,
Solution
a
SELECT a.sub_id AS post_id, coalesce(b.number_of_comments,@) AS nunber_of_comment
FROM(SELECT DISTINCT sub_id FROM submissions WHERE parent
LEFT JOIN(
SELECT parent_id, count(DISTINCT(sub_id)) AS number_of comments
id TS NULL) a
FROM submissions
GROUP BY parent_id
HAVING parent_id = any(SELECT sub_id from submissions WHERE parent_id IS NULL)) b
ON a.sub_id = b.parent_id
ORDER BY post_id
1251. Average Selling Price | Easy | (@ LeetCode
Table: Prices
| column Name | Type |
| product_id | int |
| start_date | date |
| end_date [date |
| price | int I
(product_id, start_date, end_date) is the primary key for this table.
Each row of this table indicates the price of the product_id in the period from s
For each product_id there will be no two overlapping periods. That means there wi
SS
Table: unitssold
| Column Name | Type |
| product_id | int |
| purchase date | date |
| units | int |There is no primary key for this table, it may contain duplicates.
Each row of this table indicates the date, units and product_id of each product s
=
Write an SQL query to find the average selling price for each product.
average_price should be rounded to 2 decimal places.
The query result format is in the following example:
| product_id | start_date | end_date | price |
2019-02-17 | 2019-02-28 | 5
2019-83-01 | 2619-03-22 | 20
2019-02-01 | 2019-02-20 | 15
fa |
fa |
12 |
}2 | 2019-02-21 | 2019-03-31 | 30
Unitssold table:
| product_id | purchase_date | units |
ja | 2019-02-25 | 100 |
fa | 2019-03-01 =| 15 |
|2 | 2019-02-10 | 208 |
|2 | 2019-03-22 | 3@ |
| product_id | average_price |
| 6.96 |
16.96 |
Average selling price = Total Price of Product / Number of products sold.((200 * 5) + (45 * 20) / 115 = 6.96
((200 * 15) + (30 * 30) / 230 = 16.96
Average selling price for product 1
Average selling price for product 2
Solution
.
SELECT UnttsSotd product td, ROWO(SUN(unitstprice/SM(units), 2) AS average_pr
FHOH UnitsSold WER 200N Prices
Ov unttssold.product_d = Prices. product id
fio tnitsS01d.purchase_date BETME Prices. start date AYD Prices.ené date
GROUP BY UnitsSold. product_id
Medium | (@ LeetCode
1264. Page Recommendations
Table: Friendship
| column Name | Type — |
| usert_id | int |
| user2_id [int |
(usert_id, user2_id) is the primary key for this table.
Each row of this table indicates that there is a friendship relation between user
—
Table: Likes
| Column Name | Type — |
| user_id | int |
| pageid | int(user_id, page_id) is the primary key for this table.
Each row of this table indicates that user_id likes page_id.
Write an SQL query to recommend pages to the user with user_id = 1using the
pages that your friends liked. It should not recommend pages you already liked.
Return result table in any order without duplicates.
The query result format is in the following example:
Friendship table:
| usert_id | user2_id |
hue wan
aenaukuneResult table:
| reconmended_page |
User one is friend with users 2, 3, 4 and 6.
Suggested pages are 23 from user 2, 24 from user 3, 56 from user 3 and 33 from us
Page 77 is suggested from both user 2 and user 3.
Page 88 is not suggested because user 1 already likes it.
Solution
a
SELECT DISTINCT page_id AS reconmended_page
FROM Likes
WHERE user_id IN (SELECT user2_id
FROM Friendship
WHERE user_id=1
UNION
SELECT usert_id
FROM Friendship
WHERE user2_:
1)
AND page_id NOT IN
(SELECT page_id
FROM Likes
WHERE user_id=1)
1270. All People Report to the Given Manager | Medium | @
LeetCodeTable: Employees
| column Name | Type |
| employee id | int = |
| employee_nane | varchar |
| managerid | int |
employee_id is the primary key for this table.
Each row of this table indicates that the employee with ID employee id and name e
The head of the company is the employee with employee_id = 1
—_—_—_,
Write an SQL query to find employee_id of all employees that directly or indirectly
report their work to the head of the company.
The indirect relation between managers will not exceed 3 managers as the company
is small.
Return result table in any order without duplicates.
The query result format is in the following example:
rer
Employees table:
| employee_id | employee_name | manager_id |
Boss
Alice
Bob
Daniel
Luis
3hon
Angela
RobertResult table:
| employee_id |
2
7
4
7
The head of the company is the enployee with employee id 1.
The employees with exployee_id 2 and 77 report their work directly to the head of
The employee with enployee_id 4 report his work indirectly to the head of the com
The employee with enployee_id 7 report his work indirectly to the head of the com
The employees with enployee_id 3, 8 and 9 don't report their work to head of conp
—
Solution
SELECT ti.enployee_id
FROM Employees AS t1 INNER JOIN Employees AS t2
ON t1.manager_id = t2.enployee_id
JOIN Employees AS 3
ON t2.manager_id = t3.enployee_id
WHERE t3.manager_id = 1 AND t1.employee_id
SELECT distinct enployee_id
FROM (
SELECT employee_id
FROM Employees
WHERE manager_id IN(SELECT employee_id
FROM Employees
WHERE manager_id IN
(SELECT employee_id
FROM Employees
WHERE manager_id = 1))
UNION
SELECT employee_id
FROM Employees
WHERE manager_id IN
(SELECT employee_id
FROM Employees
WHERE manager_i
UNION
»
SELECT enployee_id
FROM Employees
WHERE manager_id = 1) AS t
WHERE enployee_id
SELECT employee_id
FROM employees
WHERE manager_id = 1 AND enployee_id |
UNION
SELECT employee_id
FROM employees
WHERE manager_id = any (SELECT enployee_id
FROM employees
WHERE manager_id = 1 AND enployee_id != 1)
UNTON
SELECT employee_id
FROM employees
WHERE manager_id = any (SELECT employee_id
FROM employees
WHERE manager_id = any (SELECT enployee_id
FROM employees
WHERE manager_id = 1 AND enployee_id != 1))1280. Students and Examinations| Easy | (j LeetCode
Table: students
| column Name | Type |
| student_id | int |
| student_name | varchar |
student_id is the primary key for this table.
Each row of this table contains the ID and the name of one student in the school.
a
Table: subjects
| Column Nae | Type |
| subject_name | varchar |
subject_name is the primary key for this table.
Fach row of this table contains a name of one subject in the school.
Table: Examinations
| Column Nae | Type |
| student_id | int |
| subject_name | varchar |
There is no primary key for this table. It may contain duplicates.
Each student fron Students table takes every course from Subjects table.
Each row of this table indicates that a student with ID student_id attended the e———
Write an SQL query to find the number of times each student attended each exam.
Order the result table by studentid and subjectname.
The query result format is in the following example:
rer
Students table:
| student_id | student_name |
ja | Alice |
|2 | Bob |
[a3 | John |
le | alex |
Subjects table:
| subject_name |
| Math I
| Physics |
| Programming |
Examinations table:
| student_id | subject_name |
Math
Physics
Programming
|
|
|
Programming |
Physics Il
Math |
Math, Il
Programming |
Physics |
|
Mathja | Math
| student_id | student_name | subject_name | attended_exans |
ja | Alice | Math 13 I
ja | Alice | Physics 12 I
ja | Alice | Programing | 2 I
12 | Bob | math |a |
12 | Bob | Physics le I
12 | Bob | Programming | 1 I
ls | Alex | math le I
ls | Alex | Physics le I
ls | Alex | Progranming | @ I
| 13 | John | Math j1 |
[33 | John | Physics ja I
| a3 | John | Programming | 1 |
The result table should contain all students and all subjects.
Alice attended Math exan 3 times, Physics exam 2 times and Programming exan 1 tim
Bob attended Math exam 1 time, Progranming exam 1 time and didn't attend the Phys
Alex didn't attend any exam.
John attended Math exam 1 time, Physics exam 1 time and Programing exam 1 time.
—=—
Solution
SELECT Students.student_id, student_nane, Subjects.subject_name, COUNT(Examinatio
FROM Students JOIN Subjects
LEFT JOIN Examinations
ON Students. student_id = Examinations. student_id AND Subjects. subject_name = Exam
GROUP BY Students. student_id, subject_name
SELECT Students. student_id, student_name, Subjects. subject_name, SUM(IF(ISNULL(EXFROM Students JOIN Subjects
LEFT JOIN Examinations
ON Students. student_id = Examinations. student_id AND Subjects. subject_name = Exam
GROUP BY Students. student_id, subject_name
SELECT a.student_id AS student_id, a.student_name AS student_name, a.subject_name
FROM(
SELECT *
FROM students
CROSS JOIN subjects
GROUP BY student_id, student_name, subject_name) a
LEFT 30IN
(SELECT e.student_id, student_name, subject_name, COUNT(*) AS attended_exams
FROM examinations e JOIN students s
ON e.student_id = s.student_id
GROUP BY e.student_id, student_name, subject_name) b
ON a.student_id = b.student_id AND a.subject_name =b. subject_name
ORDER BY a.student_id ASC, a.subject_name ASC
—_—_—,
1285. Find the Start and End Number of Continuous Ranges
Medium | (@ LeetCode
Table: Logs
| column Name | Type |
id is the primary key for this table.
Each row of this table contains the ID in a log Table.
Since some IDs have been removed from Logs. Write an SQL query to find the start
and end number of continuous ranges in table Logs.Order the result table by startid.
The query result format is in the following example:
Logs table:
Result table:
| start_id | end_id I
The result table should contain all ranges in table Logs.
From 1 to 3 is contained in the table.
From 4 to 6 is missing in the table
From 7 to & is contained in the table.
Number 9 is missing in the table.
Number 1@ is contained in the table.
Solution
SELECT MIN(1og_id) AS start_id, MAX(1og_id) AS end_id
FROM(
2SELECT log_id, log_id-ROW_NUMBER() OVER (ORDER BY log_id) AS rk
FROM logs) a
GROUP BY rk
SELECT MIN(1og_ id) AS START_ID, MAX(1og id) AS END_ID
FROM (SELECT log_id,
@rank := CASE WHEN @prev = log_id-1 THEN @rank ELSE @rank+1 END AS rank,
@prev := log id AS prev
FROM Logs,
(SELECT @rank:=@, @prev:
GROUP BY rank
1) AS rows) AS tt
ORDER BY START_ID
SELECT start_id, MIN(end_id) AS end_id
FROM (SELECT t1.log_id AS start_id
FROM logs AS t1 LEFT JOIN logs AS t2
ON t1.log_id-1 = t2.1og_id
WHERE t2.log id IS NULL) tt_start join
(SELECT t1.log_id AS end_id
FROM logs AS t1 LEFT JOIN logs AS t2
ON t1.log id+1 = t2.1og_id
WHERE t2.log_id IS NULL) tt_end
WHERE start_idc=end_id
GROUP BY start_id
1294, Weather Type in Each Country | Fasy | (@ LeetCode
Table: countries
| Column Name | Type| country_id | int |
| country_name | varchar |
country_id is the primary key for this table.
Each row of this table contains the ID and the name of one country.
Table: weather
| column Name | Type |
| countryid = | int |
| weather_state | varchar |
| day [date |
(country_id, day) is the primary key for this table.
Each row of this table indicates the weather state in a country for one day.
Write an SQL query to find the type of weather in each country for November 2019.
The type of weather is Cold if the average weatherstate is less than or equal 15, Hot
if the average weatherstate is greater than or equal 25 and Warm otherwise.
Return result table in any order.
The query result format is in the following example:
Countries table:
| country_id | country_name |
usa
Australia
Peru
12
13
17
[5
ChinaWeather
| country_id |
| Morocco
| spain
table:
weather_state | day |
12
12
|2
13
13
13
Is
Is
[5
7
\7
7
8
|8
8
le
9
| 2019-11-01 |
| 2019-10-28 |
| 2019-10-27 |
| 2019-11-10 |
| 2019-11-11 |
| 2019-11-22 |
| 2019-11-07 |
| 2019-11-09 |
| 2019-11-23 |
| 2019-11-28 |
| 2019-12-01 |
| 2019-12-02 |
| 2019-11-05 |
| 2019-11-15 |
| 2019-11-25 |
| 2019-10-23 |
| 2019-12-23 |
Result table:
| country_name |
weather_type |
| usa | cold
| Austraila | Cold
| Peru | Hot
| china | Warm
| Morocco | Hot
Average
Average
Average
Average
weather_state
weather_state
weather_state
weather_state
in
in
USA in November is (15) / 1 = 15 so weather type is Cold
Austraila in November is (-2 + @ + 3) /
3
2.333 so wea
Peru in November is (25) / 1 = 25 so weather type is Hot
China in November is (16 + 18 + 21) / 3
18.333 so weatAverage weather_state in Morocco in Novenber is (25 + 27 + 31) / 3 = 27.667 so we
We know nothing about average weather_state in Spain in November so we don't incl
—
Solution
SELECT country_name, CASE WHEN AVG(weather_state) <= 15 THEN “Cold”
WHEN AVG(weather_state) >= 25 THEN "Hot
ELSE "Warn" END AS weather_type
FROM Countries INNER JOIN Weather
ON Countries.country id = Weather. country_id
WHERE MONTH(day) = 22
GoRUP BY country_name
1303. Find the Team Size | Easy | @ LeetCode
Table: Employee
| Column Name | Type |
| employee id | int = |
| team_id [ant |
employee_id is the primary key for this table.
Each row of this table contains the ID of each employee and their respective team
=
Write an SQL query to find the team size of each of the employees.
Return result table in any order.
The query result format is in the following example:Employee Table:
| employee_id | teamid |
Employees with Id 1,2,3 are part of a team with team_id
Employees with Id 4 is part of a team with team_id = 7.
Employees with Id 5,6 are part of a team with teamid = 9
SELECT employee_id, b.tean_size
FROM employee &
JOIN
¢
SELECT team_id, count(tean_id) AS team_size
FROM employee
GROUP BY team_id) b
ON e.team_id = b.team_id1308. Running Total for Different Genders | Medium | (®
LeetCode
Table: scores
| player_nane | varchar |
| gender | varchar |
| day | date |
| scorepoints | int — |
(gender, day) is the prinary key for this table
A competition is held between fenales team and males team.
Each row of this table indicates that a player_name and with gender has scored sc
Gender is ‘F' if the player is in fenales team and ‘M' if the player is in males
——
Write an SQL query to find the total score for each gender at each day.
Order the result table by gender and day
The query result format is in the following example:
Scores table:
| player_nane | gender | day | score_points |
| Aron lF | 2020-e1-01 | 17 |
| Alice LF | 2020-@1-07 | 23 I
| Bajrang = | M | 2020-e1-07 | 7 I
| Khali in | 2019-12-25 | a1 I
| Slaman i" | 2019-12-30 | 13 || 30e Im | 2e19-12-31 | 3 I
| Jose Im | 2019-12-18 | 2 I
| Priya le | 2019-12-31 | 23 |
| Priyanka | F | 2¢19-12-30 | 17 |
| gender | day | total |
2019-12-30 | 17
2019-12-31 | 4@
2020-01-01 | 57
2020-01-07 | 80
2019-12-18 | 2
2019-12-25 | 13
2019-12-38 | 26
2019-12-31 | 28
2020-01-07 | 36
B22 Ea TIT
For fenales team:
First day is 2019-12-30, Priyanka scored 17 points and the total score for the te
Second day is 2019-12-31, Priya scored 23 points and the total score for the team
Third day is 2020-01-01, Aron scored 17 points and the total score for the team i
Fourth day is 2620-01-07, Alice scored 23 points and the total score for the team
For males team:
First day is 2619-12-18, Jose scored 2 points and the total score for the team is
Second day is 2019-12-25, Khali scored 11 points and the total score for the team
Third day is 219-12-3@, Slaman scored 13 points and the total score for the team
Fourth day is 2019-12-31, Joe scored 3 points and the total score for the team is
Fifth day is 2620-61-07, Bajrang scored 7 points and the total score for the team
—=—
Solution
SELECT gender, day,
SUM(score_points) OVER(PARTITION BY gender ORDER BY day) AS totalFROM scores
GROUP BY 1,2
ORDER BY 1,2
SELECT tl.gender, t1.day, SUM(t2.score_points) AS total
FROM Scores AS t1 JOIN Scores AS t2
ON ti.gender = t2.gender
AND t1.day>=t2.day
GROUP BY t1.gender, t1.day
1321. Restaurant Growth | Medium | (@ LeetCode
Table: customer
| customerid | int |
| name | varchar |
| visited_on | date |
| amount [int |
(customer_id, visited_on) is the primary key for this table.
This table contains data about customer transactions in a restaurant.
visited_on is the date on which the customer with ID (customer_id) have visited t
amount is the total paid by a customer
—
You are the restaurant owner and you want to analyze a possible expansion (there
will be at least one customer every day).
Write an SQL query to compute moving average of how much customer paid in a7
days window (current day + 6 days before) .
The query result format is in the following example:Return result table ordered by visited_on.
average_amount should be rounded to 2 decimal places, all dates are in the format
(YYYY-MM-DD’)
Customer table:
+
| custoner_id | name
visited_on
unt |
Jhon
Daniel
jade
Khaled
aRune
Winston
Anna
Maria
Jaze
|
|
|
|
|
| elvis
|
I
|
| ahon
|
Jade
2019-@1-01
2019-01-02
2019-01-03
2019-01-04
2019-01-05
2019-01-06
2019-01-07
2019-01-08
2019-01-09
2019-01-10
2019-01-10
| 100
| 11
| 120
| 13@
| 110
| 140
| 15@
| 80
| 110
| 130
| 150
| visited_on | anount
average_amount
| 2019-01-07 | 860
| 2019-01-08 | 840
| 2019-01-09 | 840
| 2019-01-18 | 1000
122.86
128
128
142.86
Ast moving average from 2019-01-01 to
2nd moving average from 2019-01-02 to
3rd moving average from 2019-01-03 to
4th moving average from 2019-01-04 to
2019-01-07 has an average_anount of (100
2019-@1-08 has an average_anount of (110
2019-@1-09 has an average_anount of (120
2019-@1-10 has an average_anount of (130
—_—_Solution
SELECT visited_on, SUM(amount) OVER(ORDER BY visited_on ROWS 6 PRECEDING),
round(avg(amount) OVER(ORDER BY visited_on ROWS 6 PRECEDING) ,2)
FROM
(
SELECT visited_on, SUM(amount) AS amount
FROM customer
GROUP BY visited_on
ORDER BY visited_on
da
ORDER BY visited_on offset 6 ROWS
SELECT tl.visited_on,
SUM(t2.amount) AS amount,
round(avg(t2. amount), 2) AS average_anount
FROM (
SELECT visited_on, SUM(amount) AS amount
FROM Custoner
GROUP BY visited_on) AS t1
inner join
«
SELECT visited_on, SUM(amount) AS amount
FROM Custoner
GROUP BY visited_on) AS t2
ON t2.visited_on BETWEEN DATE_SUB(t1.visited_on, INTERVAL 6 DAY) and ti.visited_o
GROUP BY t1.visited_on
HAVING COUNT(1)=i
1322. Ads Performance | Easy | @ LeetCode
Table: ads| column Name | Type |
| adig [int |
| user_id | int |
| action | enum |
(ad_id, user_id) is the primary key for this table
Each row of this table contains the ID of an Ad, the ID of a user and the action
The action column is an ENUM type of (‘Clicked', ‘Viewed’, ‘Ignored')
—
‘A company is running Ads and wants to calculate the performance of each Ad.
Performance of the Ad is measured using Click-Through Rate (CTR) where:
Ad total etic
‘Adtaral clicks + Ad total views * 100,
Write an SQL query to find the ctr of each Ad.
crr=i" if Ad total clicks + Ad total vie
otherwise
Round ctr to 2 decimal points. Order the result table by ctr in descending order
and by ad_id in ascending order in case of a tie.
The query result format is in the following example:
Ads table:
| ad_id | user_id | action
Clicked
Clicked
Viewed
Ignored
Viewed
Clicked
la
l2
13
Is
la
|2
13
fa
| |
| i
| |
| Ignored |
| |
| |
| |
| |
Rayvwune
Viewed2 | | Viewed |
1 [2 | Clicked |
| 66.67 |
| 50.00 |
| 33.33 |
| 0.00 |
la
13
2
Is
for ad_id = 1, ctr = (2/(2+1)) * 100 = 66.67
for ad_id = 2, ctr = (1/(1+2)) * 100 = 33.33
for ad_id = 3, ctr = (1/(1#1)) * 100 = 50.00
for ad_id = 5, ctr = 0.00, Note that ad_id = 5 has no clicks or views.
Note that we don't care about Ignored Ads.
Result table is ordered by the ctr. in case of a tie we order them by ad_id
Solution
SELECT ad_id,
(CASE WHEN clicks+views = @ THEN @ ELSE ROUND(clicks/(clicks+views)*10@, 2) &
FROM
(SELECT ad_id,
SUM(CASE WHEN action="Clicked’ THEN 1 ELSE @ END) AS clicks,
SUM(CASE WHEN action='Viewed' THEN 1 ELSE @ END) AS views
FROM Ads
GROUP BY ad_id) AS t
ORDER BY ctr DESC, ad_id ASC
WITH t2 AS(
SELECT ad_id, SUM(CASE WHEN action in (‘Clicked') THEN 1 ELSE @ END) AS clicked
FROM ads
GROUP BY ad_id1 t2 AS
(
SELECT ad_id AS ad, SUM(CASE WHEN action in (‘Clicked", ‘Viewed') THEN 1 ELSE @ EN
FROM ads
GRouP BY ad_id
)
SELECT a.ad_id, coalesce(round((clicked +0.0)/nullif((total +0.0),0)*100,2),0) AS
FROM
(
select *
FROM t1 JOIN t2
ON ti.ad_id = t2.ad) a
ORDER BY ctr DESC, ad_id
1327. List the Products Ordered in a Period | Easy | ( LeetCode
Table: Products
| Column Name | type |
| product_id [aint |
| product_name | varchar |
| product_category | varchar |
product_id is the primary key for this table.
This table contains data about the company's products.
Table: orders| column Name | Type |
| productid | int |
| order_date | date |
| unit [int |
There is no primary key for this table. Tt may have duplicate rows.
product_id is a foreign key to Products table.
unit is the nunber of products ordered in order_date.
Write an SQL query to get the names of products with greater than or equal to 100
units ordered in February 2020 and their amount.
Return result table in any order.
The query result format is in the following example:
Products table:
| product_id | product_nane | product_category |
Ia | Leetcode solutions — | 800k |
|2 | Jewels of Stringology | 80k |
13 | HP | Laptop |
la | Lenovo | Laptop |
Is | Leetcode Kit | T-shirt |
| product_id | order_date | unit = |
Ja | 2020-02-05 | 60 I
fa | 2020-¢2-10 | 70 |
12 | 2020-01-18 | 30 I
|2 | 2e26-¢2-11 | 80 |13 | 2020-02-17 | 2 I
13 | 2020-02-24 | 3 I
[4 | 2020-03-01 | 20 |
|4 | 2020-03-04 | 30 I
[4 | 2020-03-04 | 60 I
Is | 2020-e2-25 | so |
Is | 2020-02-27 | 50 I
Is | 2020-03-01 | se |
| product_name [unit |
| Leetcode Solutions | 130 |
| Leetcode kit | 108 |
Products with product_id
Products with product_id =
1 is ordered in February a total of (6@ + 72) = 130.
2
Products with product_id = 3 is ordered in February a total of (2 +3) = 5
4
5
is ordered in February a total of 80.
Products with product_id = 4 was not ordered in February 2020.
Products with product_id = 5 is ordered in February a total of (S@ + 50) = 100.
Solution
SELECT a.product_name, a.unit
FROM
(SELECT p.product_name, SUM(unit) AS unit
FROM orders 0
JOIN products p
ON o.product_id = p.product_id
WHERE MONTH(order_date)=2 and YEAR(order_date) = 2020
GROUP BY o.product_id) a
WHERE a.unit>=100SELECT product_name, SUM(unit) AS unit
FROM Products JOIN Orders
ON Products.product_id = Orders.product_id
WHERE left(arder_date, 7) = "2020-02"
GROUP BY Products. product_id
HAVING SUM(unit)>=108
1336. Number of Transactions per Visit | Hard | (@ LeetCode
Table: visits
| column Name | Type |
| user_id [int |
| visitdate | date |
(user_id, visit_date) is the primary key for this table.
Each row of this table indicates that user_id has visited the bank in visit_date.
a
Table: Transactions
| Column Name | type |
| user_id [aint |
| transaction_date | date |
| amount [int |
There is no primary key for this table, it may contain duplicates.
Each row of this table indicates that user_id has done a transaction of amount in
It is guaranteed that the user has visited the bank in the transaction_date.(i.e
—_—_——_A bank wants to draw a chart of the number of transactions bank visitors did in one
visit to the bank and the corresponding number of visitors who have done this
number of transaction in one visit.
Write an SQL query to find how many users visited the bank and didn’t do any
transactions, how many visited the bank and did one transaction and so on.
The result table will contain two columns:
= transactions_count which is the number of transactions done in one visit.
+ visits_count which is the corresponding number of users who did
transactionscount in one visit to the bank.
“transactionscount should take all values from0 to max(transactions_count)*
done by one or more users.
Order the result table by transactions_count .
The query result format is in the following example:
Visits table:
| userid | visit_date
2020-01-01
2020-01-02
2020-01-01
2020-01-03
2020-01-04
2020-@1-11
2020-@1-25
2020-@1-28
| |
| |
| |
| |
Ia | 2020-e1-02
| |
| |
| |
i |
| |
|
|
|
I
|
2020-01-03 |
|
|
|
|
Transactions table:
e
| user_id | transaction_date | amount |ja | 2020-01-02 | 20 |
2 | 2020-01-03 | 22 |
\7 | 2020-01-11 | 232 |
fa | 2020-01-04 \7 |
le | 2020-01-25 13]
l9 | 2020-01-25 lee |
Is | 2020-01-28 Ja |
|9 | 2020-01-25 | 99 |
* For transactions_count = @, The visits (1, "2020-e1-01"), (2, "2020-@1-@2"), (1
* For transactions_count = 1, The visits (2, "2020-01-03"), (7, "2¢2e-@1-11"), (8
* For transactions count = 2, No customers visited the bank and did two transacti
* For transactions_count = 3, The visit (9, "2620-01-25") did three transactions
* For transactions _count >= 4, No customers visited the bank and did more than th
——————
The chart drawn for this example is as follows:
BANK TRANSACTIONS
BVists
5 Vists
4 Vists -
3Vists
2Vists
Wists| Zz
O Transactions ‘Transactions 2 Transactions 3 Transactions
Solution
WITH RECURSIVE t1 AS(
SELECT visit_date,
COALESCE (num_visits,@) as num_visits,
COALESCE(num_trans,@) as num_trans
FROM ((
SELECT visit_date, user_id, COUNT(*) as num_visits
FROM visits
GROUP BY 1, 2) AS a
LEFT JOIN
(
SELECT transaction_date,
user_id,
count(*) as nun_trans
FROM transactions
GROUP BY 1, 2) AS b
ON a.visit_date = b.transaction_date and a.user_id = b.u
»
+2 AS (
SELECT MAX(num_trans) as trans
FROM t1
UNION ALL
SELECT trans-1
FROM t2
WHERE trans >= 1)
SELECT trans as transactions_count,
COALESCE(visits_count,@) as visits_count
FROM t2 LEFT JOIN (
SELECT num_trans as transactions_count, COALESCE (COUNT(*),@)
FROM t1.
GROUP BY 1ORDER BY 1) AS a
ON a.transactions_count = t2.trans
ORDER BY 1
1341. Movie Rating | Medium | ( LeetCode
Table: Movies
| Column Name | Type — |
| movie_id | int |
| title | varchar |
movie_id is the primary key for this table.
title is the name of the movie.
Table: users
| column Name | Type |
| user_id [ant |
| name | varchar |
user_id is the primary key for this table.
Table: vovie_ rating
| Column Wane | Type| movie_id [int |
| user_id | int |
| rating [ant |
| created_at | date |
(movie_id, user_id) is the primary key for this table.
This table contains the rating of a movie by a user in their review.
created_at is the user's review date.
Write the following SQL query:
= Find the name of the user who has rated the greatest number of the movies.
In case of a tie, return lexicographically smaller user name.
« Find the movie name with the highest average rating in February 2020.
In case of a tie, return lexicographically smaller movie name..
Query is returned in 2 rows, the query result format is in the following example:
Movies table:
| movie id | title |
fa | Avengers |
12 | Frozen 2 |
13 | Joker |
| Daniel
| Monica
| Maria
| JamesMovie Rating table:
| movie id | user_id | rating | created_at |
| 2020-01-12 |
| 2e20-e2-11 |
| 2020-02-12 |
| 2e20-e1-01 |
| 2020-02-17 |
| 2@20-e2-61 |
| 2020-03-01 |
| 2¢20-e2-22 |
| |
ja
fa
[a
fa
12
|2
12
13
13
2020-02-25
Result table:
| results |
| Daniel I
| Frozen 2 |
Daniel and Maria have rated 3 movies ("Avengers", "Frozen 2" and "Joker") but Dan
Frozen 2 and Joker have a rating average of 3.5 in February but Frozen 2 is small
—
Solution
(SELECT name AS results
FROM Movie Rating JOIN Users
ON Movie Rating.user_id = Users.user_id
GROUP BY Movie_Rating.user_id
ORDER BY count(1) DESC, name
LIMIT 1)
UNION ALL(SELECT title AS results
FROM Movie Rating JOIN Movies
ON Movie Rating.movie_id = Movies.movie_id
WHERE left(created_at, 7) = "2020-02
GROUP BY Movie_Rating.movie_id
ORDER BY avg(rating) DESC, title
LIMIT 1
)
SELECT name AS results
FROM
(SELECT a.nane
FROM
SELECT name, count(*),
rank() OVER(ORDER BY count(*) DESC) AS rk
FROM movie_rating m
JOIN users u
ON m.user_id = u.user_id
GROUP BY name, m.user_id
ORDER BY rk, name) a
LIMIT 4)
UNION
(SELECT title
FROM(
SELECT title, round(avg(rating),1) AS rnd
FROM movie_rating m
JOIN movies u
on m.novie_id = u.movie_id
WHERE month(created_at) = 2
GROUP BY title
ORDER BY rnd DESC, title) b
LIMIT 4)) as 4
1350. Students With Invalid Departments
Table: Departments
Easy | @ LeetCode| column wane | Type |
| id [int |
| name | varchar |
id is the primary key of this table.
The table has information about the id of each department of a university.
Table: students
| Column Name | Type =|
| id | int |
| name | varchar |
| department_id | int |
id is the primary key of this table.
The table has information about the id of each student at a university and the id
—,
Write an SQL query to find the id and the name of all students who are enrolled in
departments that no longer exists.
Return the result table in any order.
The query result format is in the following example:
Departments tabl
| Electrical Engineering |
1
7 | Computer Engineering || 13. | Bussiness Administration |
Students table:
| id | nare | department_id |
[23 | Alice [a |
14 | Bob Ll? \
15 | Jennifer | 13 |
|2 [John | a4 \
14 | Jasmine | 77 |
[3 | Steve | 74 \
le | luis la |
[8 | Jonathan | 7 \
17 | daiana | 33 \
[a1 | Madetynn | a |
12 | John |
17 | Daiana |
| 4 | Jasmine |
[3 | Steve |
John, Daiana, Steve and Jasmine are enrolled in departments 14, 33, 74 and 77 res
—SYSYS —
Solution
SELECT s.id, s.name
FROM students s LEFT JOINdepartments d
ON s.department_id = d.id
WHERE d.name IS NULL;
SELECT id, name
FROM Students
WHERE department_id NOT IN
(SELECT id FROM Departments)
1355,
Activity Participants | Medium | (j LeetCode
Table: Friends
| column Name | Type |
| ad [aint |
| name | varchar |
| activity | varchar |
id is the id of the friend and primary key for this table.
name is the name of the friend.
activity is the name of the activity which the friend takes part in.
Table: activities
| Column Name | Type =|
| id | int |
| name | varchar |
id is the primary key for this table.
name is the name of the activity.Write an SQL query to find the names of all the activities with neither maximum, nor
minimum number of participants.
Return the result table in any order. Each activity in table Activities is performed by
any person in the table Friends.
The query result format is in the following example:
tet
Friends table:
| id | name | activity I
|.1 | Jonathan b. | Eating |
12 | Jade w. | Singing |
[3 | Victor 3. | Singing |
|4 | elvisQ. | Eating |
[5 | Daniel A. | Eating |
16 | Bob B. | Horse Riding |
+
| id | name |
| Eating |
| Singing |
[3 | Horse Riding |
| Singing |
Eating activity is performed by 3 friends, maximum number of participants, (JonatHorse Riding activity is performed by 1 friend, minimum number of participants, (
Singing is performed by 2 friends (Victor J. and Jade W.)
Solution
WITH CTE AS
—
(SELECT COUNT(*) AS cnt, activity FROM Friends GROUP BY activity)
SELECT activity FROM CTE
WHERE cnt NOT IN
(SELECT MAX(cnt) FROM CTE
UNION ALL.
SELECT MIN(cnt) FROM CTE)
WITH £1 AS(
SELECT MAX(a.total) AS total
FROM(
SELECT activity, COUNT(*) AS total
FROM friends
GROUP BY activity) a
UNION ALL
SELECT MIN(b.total) AS low
FROM(
SELECT activity, COUNT(*) AS total
FROM friends
GROUP BY activity) b)
+2-AS
(
SELECT activity, COUNT(*) AS total
FROM friends
GROUP BY activity
SELECT activityFROM 1 RIGHT JOIN t2
ON t1.total = t2.total
WHERE t1.total is null
1364, Number of Trusted Contacts of a Customer | Medium | (@
LeetCode
Table: Customers
| Column Name | Type |
| customer_id | int |
| customer_nane | varchar |
| email | varchar |
customer_id is the primary key for this table.
Each row of this table contains the name and the email of a customer of an online
=
Table: contacts
| column Wane | Type |
| user_id | id \
| contact_name | varchar |
| contact_enail | varchar |
(user_id, contact_enail) is the primary key for this table.
Each row of this table contains the nane and email of one contact of customer wit
This table contains information about people each customer trust. The contact may
—
Table: Invoices| column Name | Type |
| invoice id | int = |
| price | int |
| user_id [ant |
invoice_id is the primary key for this table.
Each row of this table indicates that user_id has an invoice with invoice_id and
=—
Write an SQL query to find the following for each invoice_i
» customer_name: The name of the customer the invoice is related to.
= price: The price of the invoice.
= contacts_cnt: The number of contacts related to the customer.
= trustedcontactsent: The number of contacts related to the customer and at the
same time they are customers to the shop. (i.e His/Her email exists in the
Customers table.) Order the result table by invoice_id.
The query result format is in the following example:
Customers table:
| custoner_id | customer_name | email |
ja | Alice | [email protected] |
|2 | Bob | [email protected] |
| 13 | John | [email protected] |
6 | Alex | [email protected] |
Contacts table:
+e
| user_id | contact_name | contact_email |
Ia | Bob | [email protected] |ja | John | [email protected] |
fa | jaa | [email protected] |
|2 | omar | [email protected] |
2 | Meir | [email protected] |
ls | Alice | alicegleetcode.com |
invoice_id | price | user_id
l77 100 J 4 I
| 88 | 200 Ja I
| 99 | 300 | 2 I
| 66 | 400 | 2 I
| 55 | sea | 43 I
| 4a |e |6 |
Result table:
| invoice_id | customer_name | price | contacts_cnt | trusted_contacts_cnt |
| 44, | Alex [ee |1 fa |
| 55 | ohn | 500 | 0 le |
| 66 | Bob | 400 | 2 le |
|77 | Alice | 100 | 3 12 |
| 88 | Alice | 200 | 3 [2 |
| 99 | Bob | 300 | 2 le |
Alice has three contacts, two of them are trusted contacts (Bob and John).
Bob has two contacts, none of then is a trusted contact.
Alex has one contact and it is a trusted contact (Alice).
John doesn't have any contacts.
Solution
SELECT invoice_id, customer_name, price,
COUNT(Contacts.user_id) AS contacts_cnt,SUM(CASE WHEN Contacts.contact_nane IN
(SELECT customer_name FROM Customers)
THEN 1 ELSE @ END) AS trusted_contacts_cnt
FROM Invoices INNER JOIN Customers ON Invoices.user_id = Customers. customer_id
LEFT JOIN Contacts ON Customers.customer_id = Contacts.user_id
GROUP BY Invoices. invoice_id, customer_name
ORDER BY Invoices. invoice_id
1369. Get the Second Most Recent Acti
ivity | Hard | @ LeetCode
Table: useractivity
| column Name | Type |
| usernane | varchar |
| activity | varchar |
| startoate | Date |
| endbate | pate |
This table does not contain primary key.
This table contain information about the activity performed of each user in a per
A person with usernane performed a activity fron startoate to endoate.
=—
Write an SQL query to show the second most recent activity of each user.
If the user only has one activity, return that one.
Auser can’t perform more than one activity at the same time. Return the result table
in any order.
The query result format is in the following example:UserActivity table:
| username | activity | startDate | endbate |
| Alice | Travel | 2@20-02-12 | 2020-02-20 |
| Alice | Dancing | 2020-02-21 | 2020-02-23 |
| Alice | Travel | 2@20-02-24 | 2020-02-28 |
| Bob | Travel | 2020-02-11 | 2620-02-18 |
Result table:
| username | activity | startbate | endDate |
| Alice | Dancing | 2020-02-21 | 2020-02-23 |
| Bob | Travel | 2020-02-11 | 2020-02-18 |
The most recent activity of Alice is Travel from 2626-@2-24 to 2020-02-28, before
Bob only has one record, we just take that one.
Solution
(SELECT *
FROM Useractivity
GROUP BY username
HAVING count(1) = 1)
UNION
(SELECT a.*
FROM UserActivity AS a LEFT JOIN UserActivity AS b
on a.username = b.username AND a.endDatecb.endbate
GROUP BY a.username, a.endDate
HAVING count(b.endDate) = 1)1378. Replace Employee ID With The Unique Identifier | Easy |
@ LeetCode
Table: Employees
| column Name | Type |
| ad [ant |
| name | varchar |
id is the primary key for this table.
Each row of this table contains the id and the name of an employee in a company.
Table: enployeeunt
| column Nave | Type |
| ad [int |
| unique_id | int |
(id, unique_id) is the primary key for this table.
Each row of this table contains the id and the corresponding unique id of an empl
——T—
Write an SQL query to show the unique ID of each user, If a user doesn't have a
unique ID replace just show null.
Return the result table in any order.
The query result format is in the following example:
Employees table:| id | name |
1 | Alice
7 | Bob
9@ | Winston
| |
| |
Jaa | Meir |
| |
[3° | Jonathan |
EmployeeUNI table:
| id | unique_id |
| uniqueid | name |
| nuit J alice |
| nuit | Bob I
l2 [Meir |
13 | Winston |
ja | Jonathan |
Alice and Bob don’t have a unique ID, We will show null instead.
The unique ID of Meir is 2.
The unique ID of Winston is 3.
The unique ID of Jonathan is 1.
SolutionSELECT unique_id, name
FROM Employees
LEFT JOIN EmployeeUNI
ON Employees.id = EmployeeUNI.id
1384. Total Sales Amount by Year | Hard | LeetCode
Table: Product
-+ | Column Name | Type | +-- + |
productid | int | | productname | varchar | +- + producti is
the primary key for this table. productname is the name of the product.
+
+
Table: sales
| Column Wane | type |
| product_id Jane |
| period_start | varchar |
| period_end | date |
| average daily sales | int |
product_id is the primary key for this table.
period_start and period_end indicates the start and end date for sales period, bo
‘The average_daily sales column holds the average daily sales amount of the items
—
Write an SQL query to report the Total sales amount of each item for each year, with
corresponding product name, productid, productname and report year.
Dates of the sales years are between 2018 to 2020. Return the result table ordered
by productid and reportyear.
The query result format is in the following example:Product table:
| product_id | product_nane |
| Le Phone |
la
12 J tc t-shirt |
13 | Le Keychain |
| product_id | period_start | period_end | average_daily sales |
ha | 2019-01-25 | 2019-02-28 | 100 |
12 | 2018-12-01 | 2020-01-01 | 10 |
13 | 2019-12-01 | 2020-01-31 | 1 |
| product_id | product_nane | report_year | total_anount |
fa | Le Phone | 2019 | 3500 |
12 J lc t-shirt | 2018 | 310 |
[2 | Lc T-shirt | 2019 | 3650 |
12 [tc t-shirt | 2020 | 10 |
13 | Le Keychain | 2019 | 31 |
13 | Lc Keychain | 2020 | 34 |
LC Phone was sold for the period of 2019-01-25 to 2019-02-28, and there are 35 da
LC T-shirt was sold for the period of 2018-12-01 to 2020-01-01, and there are 31,
LC Keychain was sold for the period of 2019-12-@1 to 2020-01-31, and there are 31
—_—_—,
SolutionSELECT
b.product_id,
a. product_nane,
a.yr AS report_year,
case
WHEN YEAR(b.period_start:
EAR(b.period_end) AND a.yr=YEAR(b.period_start
WHEN a.yr=YEAR(b.period_start) THEN DATEDIFF(DATE_FORMAT(b.period start,
WHEN a.yr=YEAR(b.period_end) THEN DAYOFYEAR(b.period_end)
WHEN a.yr>YEAR(b.period_start) AND a.yr @
ORDER BY b.product_id,a.yr
1393. Capital Gain/Loss
Medium | (@ LeetCode
Table: stocks
| column Name | Type — |
| stock_name | varchar |
| operation | enum |
| operation_day | int |
| price [ant |(stock_name, day) is the primary key for this table.
The operation column is an ENUM of type (‘Sell', ‘Buy')
Each row of this table indicates that the stock which has stock_name had an opera
It is guaranteed that each ‘Sell’ operation for a stock has @ corresponding ‘Buy’
—
Write an SQL query to report the Capital gain/loss for each stock.
The capital gain/loss of a stock is total gain or loss after buying and selling the stock
one or many times.
Return the result table in any order.
The query result format is in the following example:
Stocks table:
| stock_name | operation | operation_day | price |
| Leetcode | Buy Ja | 1800 |
| Corona Masks | Buy 12 Jae |
| Leetcode | sell Is | 9e0@ |
| Handbags | Buy |a7 | 30000 |
| Corona Masks | Sell 13 | 1e1e |
| Corona Masks | Buy [4 | 1080 |
| Corona Masks | Sell | | see |
| Corona Masks | Buy lé | 1000 |
| Handbags | sell | 29 | 7eee |
| Corona Masks | Sell | 10 | 18000 |
-23000
| stock_name | capital_gain_loss |
| Corona Masks | 9500 |
| Leetcode | 8000 |
| |
| HandbagsLeetcode stock was bought at day 1 for 10@$ and was sold at day 5 for 9800$. Cap
Handbags stock was bought at day 17 for 30000$ and was sold at day 29 for 7e00$.
Corona Masks stock was bought at day 1 for 10$ and was sold at day 3 for 1e10$. I
|
Solution
2
SELECT stock_name,
SUM(CASE WHEN operation = ‘Buy’ THEN -price ELSE price END) AS capital_gai
FROM Stocks
GROUP BY stock_name;
SELECT stock_name, (one-two) AS capital_gain_loss
FROM,
(SELECT stock_nane, sum(price) AS one
FROM stocks
WHERE operation = ‘sell*
GROUP BY stock_nane) b
LEFT 301N
(SELECT stock_name AS name, sum(price) AS two
FROM stocks
WHERE operation = “Buy”
GROUP BY stock_name) ¢
ON b.stock_nane = c.nane)
ORDER BY capital_gain_loss DESC
1398. Customers Who Bought Products A and B but Not C |
Medium | (@ LeetCode
Table: customers| Column Name | type |
| custoner_id [ant |
| customer_nane | varchar |
customer_id is the primary key for this table.
customer_nane is the name of the customer.
Table: orders
| Column Name | Type |
| order_id | int |
| customerid | int |
|
| product_name | varchar
order_id is the primary key for this table.
customer_id is the id of the customer who bought the product "product_name".
Write an SQL query to report the customerid and customername of customers who
bought products ‘A’, "B” but did not buy the product “C” since we want to
recommend them buy this product.
Return the result table ordered by customer_id.
The query result format is in the following example.
Customers table:
| custoner_id | customer_nane |
| Daniel |
1
2 | Diana |3 | Elizabeth |
4 | dhon |
| orderid | customer_id | product_name |
18
20
38
40
6@
70
80
98
Reu en eee
| |
| |
| |
| |
| se |
| |
| |
| |
| |
noe >> noe >
Result table:
| customer_id | customer_name |
13 | Elizabeth |
Only the customer_id with id 3 bought the product A and B but not the product C.
Solution
WITH t1 AS
(
SELECT customer_id
FROM orders
WHERE product_name = 'B' AND
custoner_id IN (SELECT customer_idFROM orders
WHERE product_name = 'A‘))
SELECT t1.customer_id, ¢.customer_name
FROM t1 JOIN customers ¢
ON t1.customer_id = c.customer_id
WHERE t1.customer_id != all(SELECT customer_id
FROM orders
WHERE product_nane = 'C')
SELECT *
FROM Customers
WHERE customer_id IN
(SELECT DISTINCT customer_id
FROM Orders
WHERE product_name
) AND
customer_id IN
(SELECT DISTINCT customer_id
FROM Orders
WHERE product_name
) AND
customer_id NOT IN
(SELECT DISTINCT customer_id
FROM Orders
WHERE product_name
)
ORDER BY customer_id
SELECT Customers.*
FROM (
SELECT custoner_id,
sum(CASE WHEN product_name = ‘A’ THEN 1 ELSE @ END) AS product_a,
sum(CASE WHEN product_name = ‘8’ THEN 1 ELSE @ END) AS product_b
FROM Orders
GROUP BY customer_id) AS t JOIN Customers
ON t.customer_id = Customers. customer_id
WHERE t.product_a>@ AND product_b >@ AND Customers.customer_id NOT IN (SELECT DISTINCT custoner_id
FROM Orders
WHERE product_nane = ‘C')
ORDER BY Custoners. customer_id
1407. Top Travellers | Easy | (@ LeetCode
Table: users
| colunn Name | type |
| id | int |
| name | varchar |
id is the primary key for this table.
name is the name of the user.
Table: Rides
| column Name | Type |
| ad [int |
| user_id | int |
| distance [int |
id is the primary key for this table.
city_id is the id of the city who bought the product “product_name”.
Write an SQL query to report the distance travelled by each user.
Return the result table ordered by travelled_distance in descending order, if two or
more users travelled the same distance, order them by their nane in ascendingorder.
The query result format is in the following example.
ter
Users table
Alice
Bob
Alex
Lee
Jonathan
Elvis
| |
| |
| |
| Donald |
| |
| |
| |
+
| id | userid | distance
Result table:
| name | travelled_distance |
| Elvis | 450 |
| Lee | 450 I
| Bob | 317 |Jonathan | 312
| I
| Alex | 222 |
| Alice | 120 |
| Donald | @ |
Elvis and Lee travelled 45@ miles, Elvis is the top traveller as his name is alph
Bob, Jonathan, Alex and Alice have only one ride and we just order them by the to
Donald didn't have any rides, the distance travelled by him is 0.
—
Solution
SELECT U.name AS name, COALESCE(SUM(R.distance),@) AS travelled_distance
FROM Users U LEFT JOIN Rides R
ON R.user_id = U.id
GROUP BY name
ORDER BY travelled_distance DESC, name
SELECT name, IFNULL(SUM(distance), @) AS travelled_distance
FROM Users LEFT JOIN Rides
ON Users.id = Rides.user_id
GROUP BY Users. id
ORDER BY travelled distance DESC, name
SELECT name, SUM(IF(ISNULL(distance), @, distance) AS travelled_distance
FROM Users LEFT JOIN Rides
ON Users.id = Rides.user_id
GROUP BY Users. id
ORDER BY travelled distance DESC, name
1412. Find the Quiet Students in All Exams | Hard | (@ LeetCodeTable: student
| student_id [ant |
| student_name | varchar |
student_id is the primary key for this table.
student_name is the name of the student.
Table: Exan
| column Name | Type =|
| exam_id | int |
| studentid | int |
| score Jint |
(exam_id, student_id) is the primary key for this table.
Student with student_id got score points in exam with id exam_id.
A “quite” student is the one who took at least one exam and didn’t score neither the
high score nor the low score.
Write an SQL query to report the students (studentid, studentname) being “quiet” in
ALL exams.
Don't return the student who has never taken any exam. Return the result table
ordered by student_id.
The query result format is in the following example.Student table:
| student_id | student_name |
fa | baniel |
12 | Jade I
13 | Stella |
la | Jonathan |
1s | win |
| examid | student_id | score |
| 10 | 1 | 7e |
| 18 12 | 8 |
110 | 3 | 98 |
| 20 | 1 | 86 I
| 30 | 1 | 7e |
| 30 13 | 8 |
| 30 | 4 | 98 |
| 40 | 1 | 6e I
| 40 | 2 | 78 |
| 40 i 4 | 8 |
| student_id | student_name |
l2 | ade |
For exam 1: Student 1 and 3 hold the lowest and high score respectively.
For exam 2: Student 1 hold both highest and lowest score.
For exam 3 and
Studnet 1 and 4 hold the lowest and high score respectively.
Student 2 and 5 have never got the highest or lowest in any of the exam.Since student 5 is not taking any exam, he is excluded from the result.
So, we only return the information of Student 2.
Solution
WITH th AS(
SELECT student_id
FROM
(SELECT *
MIN(score) OVER(PARTITION BY exam_id) AS least,
MAX(score) OVER(PARTITION BY exan_id) AS most
FROM exam) a
WHERE least = score OR most = score)
SELECT DISTINCT student_id, student_nane
FROM exam JOIN student
USING (student_ia)
WHERE student_id != al1(SELECT student_id FROM t1)
order by 1
SELECT DISTINCT Student.*
FROM Student INNER JOIN Exam
ON Student. student_;
d = Exam.student_
WHERE student. student_id NOT IN
(SELECT e1.student_id
FROM Exam AS e1 INNER JOIN
(SELECT exam_id, MIN(score) AS min_score, MAX(score) AS max_score
FROM Exan
GROUP BY exam_id) AS €2
ON el.exam_id = e2.exan_id
WHERE e1.score = e2.min_score OR e1.score = e2.nax_score)
ORDER BY student_id1421. NPV Queries | Medium | (@ LeetCode
Table: nev
| column Name | Type |
| id Jint |
| year | int |
| npy Jane |
(id, year) is the primary key of this table.
The table has information about the id and the year of each inventory and the cor
—
Table: queries
| column Name | Type
(id, year) is the primary key of this table.
The table has information about the id and the year of each inventory query.
Write an SQL query to find the npv of all each query of queries table.
Return the result table in any order.
The query result format is in the following example:
NPV table:
lid | year | npv[1 | 2018 | 18 |
17 | 2020 |30 |
}13 | 2019 | 40 |
Ja | 2e19 | a3
| 2 | 2008 Jaz |
13 | 2009 |12 |
[11 | 202e | 99 |
17 | 219 |e |
| 2019 |
| 2008 |
| 2009 |
| 2018 |
| 2019 |
| 2020 |
| |
2019
}a | 2e19 a3
|2 | 2008 Jaz |
13 | 2009 Jaz |
17 | 218 |e |
17 | 219 |e \
17 | 202e | 3e |
}43 | 2019 | 40 |
The npv value of (7, 2018) is not present in the NPV table, we consider it @.
The npv values of all other queries can be found in the NPV table.Solution
SELECT q.id, q.year, COALESCE(n.npv,@) AS npy
FROM queries q
LEFT JOIN npv n
ON q.id = n.id AND q.year=n.year
SELECT Queries.*, IF(ISNULL(npv), ®, npv) AS npv
FROM Queries LEFT JOIN NPV
ON Queries.id = NPV.id AND Queries.year = NPV.year
1435. Create a Session Bar Chart | Easy | (@ LeetCode
Table: sessions
| Column Name | Type |
| session_id | int |
| duration [ant |
session_id is the primary key for this table.
duration is the time in seconds that a user has visited the application.
You want to know how long a user visits your application. You decided to create bins
of “[0-5>", “[5-10>", “[10-15>” and “15 minutes or more” and count the number of
sessions on it.
Write an SQL query to report the (bin, total) in any order.The query result format is in the following example.
Sessions table:
| session_id | duration |
Ia | 3e |
[2 | 298 |
13 | 348 |
|4 | 580 |
Is | 1600 |
| bin | total |
| [e-5> 13 I
| [s-16> Ia |
| [eas | @ |
| 15 or more | 2 I
For session_id 1, 2 and 3 have a duration greater or equal than @ minutes and les
For session_id 4 has a duration greater or equal than 5 minutes and less than 10
There are no session with a duration greater or equial than 10 minutes and less t
For session_id 5 has a duration greater or equal than 15 minutes.
Solution
(SELECT "[@-5>" AS bin,
‘SUM(CASE WHEN duration/6® < 5 THEN 1 ELSE @ END) AS total FROM Sessions)
UNTON
(SELECT "[5-1@>" AS bin,SUM(CASE WHEN ((duration/6® >= 5) AND (duration/6@ < 1@)) THEN 1 ELSE @ END) AS
UNION
(SELECT *[1@-15>" AS bin,
SUM(CASE WHEN ((duration/6@ >= 18) AND (duration/6@ < 15)) THEN 1 ELSE @ END) AS
UNION
(SELECT "15 or more’ AS bin,
SUM(CASE WHEN duration/6@ >= 15 THEN 1 ELSE @ END) AS total FROM Sessions)
SELECT '[0-5>' AS bin, count(1) AS total
FROM Sessions
WHERE duration>=@ AND duration < 300
UNTON
SELECT '[5-10>' AS bin, count(1) AS total
FROM Sessions
WHERE duration>=300 AND duration < 600
UNION
SELECT '[10-15>" AS bin, count(1) AS total
FROM Sessions
WHERE duration>=600 AND duration < 90
UNTON
SELECT ‘15 or more’ AS bin, count(1) AS total
FROM Sessions
WHERE duration >= 900
1440. Evaluate Boolean Expression | Medium | ( LeetCode
Table variables :
| column Wane | Type
| name | varchar |
| value | int |name is the primary key for this table.
This table contains the stored variables and their values.
Table expression:
| column Name | Type |
| left_operand | varchar |
| operator | enun |
| right_operand | varchar |
(1eft_operand, operator, right_operand) is the primary key for this table.
This table contains a boolean expression that should be evaluated.
operator is an enum that takes one of the values ("<', '>', ‘=')
The values of left_operand and right_operand are guaranteed to be in the Variable
=
Write an SQL query to evaluate the boolean expressions in expressions table.
Return the result table in any order.
The query result format is in the following example.
Variables table:
| name | value |
Expressions table:
| leFt_operand | operator | right_operand || left_operand | operator | right_operand | value
false
true
false
true
false
true
As shown, you need find the value of each boolean exprssion in the table using th
—
Solution
WITH €1 AS
SELECT e.left_operand, e.operator, e.right_operand, v.value AS left_val, v_1.valu
FROM expressions &
JOIN variables v
ON venane = e.left_operand
JOIN variables v_1
ON v_i.name = e.right_operand)
SELECT t1.left_operand, t1.operator, t1.right_operand
CASE WHEN t1.operator = '<' THEN (SELECT ti.left_val< ti.right_val!
‘>! THEN (SELECT t1.left_val > t1.right_val)
‘2! THEN (SELECT ti.left_val = t1.right_val)
WHEN t1.operator
WHEN t1.operatorELSE FALSE
END AS VALUE
FROM t1.
SELECT t.left_operand, t.operator, t.right_operand,
(CASE WHEN vi_value>v2.value AND operator = '>' THEN “true”
WHEN v1_valuev2.value, “true”, false")
THEN IF(v1_value=1000 AND salary_max<=10000 THEN Salaries. salary *
ELSE Salaries.salary * @.51 END, @) AS salary
FROM Salaries INNER JOIN (
SELECT company_id, MAX(salary) AS salary_max
FROM Salaries
GROUP BY company_id) AS t
ON Salaries.company_id = t.company_id
1479, Sales by Day of the Week | Hard | (@ LeetCode
Table: orders
| Column Name | Type |
| order_id | int |
| customerid | int |
| order_date | date |
| itemid | varchar |
| quantity | int |
(ordered_id, item_id) is the primary key for this table.
This table contains information of the orders placed.
order_date is the date when item_id was ordered by the customer with id customer_
=Table: rtems
| itemid | varchar |
| item_name | varchar |
| item_category | varchar |
item_id is the primary key for this table.
item_nane is the name of the item.
item_category is the category of the item.
You are the business owner and would like to obtain a sales report for category
items and day of the week.
Write an SQL query to report how many units in each category have been ordered
‘on each day of the week.
Return the result table ordered by category.
The query result format is in the following exampl
orders table:
| order_id | custoner_id | order_date | iten_id | quantity |
+
ia ha | 2020-06-01 | 1 | 10 |
12 ja | 2020-06-08 | 2 | 10 |
13 12 | 2020-06-02 | 1 Is |
ja [3 | 2020-06-03 | 3 Is |
Is la | 2020-06-04 | 4 ha |
Is [4 | 2020-06-05 | 5 Is |
17 Is | 2020-06-05 | 1 | 10 |
|3 Is | 2020-06-14 | 4 Is |
19 Is | 2020-06-21 | 3 Is |Items table
| itenid | item_name | iten_category |
Ia | Le Alg. Book — | Book I
12 | Lc DB. Book — | Book I
13 | Le SmarthPhone | Phone Il
14 | Lc Phone 2828 | Phone I
[5 | Le SmartGlass | Glasses |
ls | Le T-shirt XL | T-Shirt I
Result table:
| category | Monday | Tuesday | Wednesday | Thursday | Friday | Saturd
| Book | 26 Is le le | 1¢ le
| Glasses | @ le le le Is le
| Phone le le Is fa le le
| T-shirt | @ le le le le le
On Monday (2020-06-01, 2020-06-08) were sold a total of 2 units (10 + 10) in the
On Tuesday (2020-06-02) were sold a total of 5 units in the category Book (id
On Wednesday (2020-06-03) were sold a total of 5 units in the category Phone (ids
On Thursday (2020-06-04) were sold a total of 1 unit in the category Phone (ids:
1, 2) and 5
On Friday (2020-@6-5) were sold 1@ units in the category Book (id:
On Saturday there are no items sold.
On Sunday (202@-@6-14, 2020-06-21) were sold a total of 1@ units (5 +5) in the ca
There are no sales of T-Shirt.
Solution
WITH t1 ASC
SELECT DISTINCT item_category,
CASE WHEN dayname(order_date)='Monday’ THEN SUM(quantity) OVER(PARTITION BY item_CASE WHEN dayname(order_date:
CASE WHEN dayname(order_date:
CASE WHEN dayname(order_date:
CASE WHEN dayname(order_date:
CASE WHEN dayname(order_date:
CASE WHEN dayname(order_date:
FROM orders 0
Tuesday’ THEN SUM(quantity) OVER(PARTITION BY item
‘Wednesday’ THEN SUM(quantity) OVER(PARTITION BY it
Thursday’ THEN SUM(quantity) OVER(PARTITION BY ite
"Friday’ THEN SUM(quantity) OVER(PARTITION BY item
"saturday’ THEN SUM(quantity) OVER(PARTITION BY ite
Sunday’ THEN SUM(quantity) OVER(PARTITION BY item_
RIGHT JOIN items i
USING (item_id))
SELECT item_category AS category, SUM(Monday) AS Monday, SUM(Tuesday) AS Tuesday,
SUM(Friday) Friday, SUM(Saturday) Saturday, SUM(Sunday) Sunday
FROM t1.
GROUP BY item_category
1484. Group Sold Products By The Date | Easy | (@j LeetCode
Table activities:
| Column Name | Type |
| sell_date | date |
| product | varchar |
There is no primary key for this table, it may contains duplicates.
Each row of this table contains the product name and the date it was sold in a ma
=
Write an SQL query to find for each date, the number of distinct products sold and
their names.
The sold-products names for each date should be sorted lexicographically.
Return the result table ordered by sell_dateThe query result format is in the following example.
ter
Activities tabl
| sell_date | product |
2020-05-30 | Headphone
2028-06-01 | Pencil
2020-06-02 | Mask
| | |
| | |
| | |
| 2020-05-30 | Basketball |
| | |
| | |
| | |
2020-06-01 | Bible
2028-06-02 | Mask
2020-05-30 | T-Shirt
| sell_date | num_sold | products |
| 2020-05-30 | 3 | Basketball, Headphone,T-shirt |
| 2¢20-06-¢1 | 2 | Bible, Pencil |
| 2020-06-02 | 1 | Mask |
For 2020-05-30, Sold items were (Headphone, Basketball, T-shirt), we sort them le
For 2020-06-01, Sold items were (Pencil, Bible), we sort them lexicographically a
For 2020-06-02, Sold item is (Masks), we just return it.
—_—,
Solution
a
SELECT sell_date, COUNT(DISTINCT product) AS num_sold, group_concat(DISTINCT prod
FROM activities
GROUP BY 1
ORDER BY 11495. Friendly Movies Streamed Last Month | Easy | @
LeetCode
Table: TvProgram
| column Name | Type |
+
| programdate | date |
| content_id = | int |
|
| channel, | varchar’
+ +
(progran_date, content_id) is the primary key for this table.
This table contains information of the programs on the TV.
content_id is the id of the program in some channel on the TV.
Table: content
| Column Name | type |
| content_id | varchar |
| title | varchar |
| Kids_content | enum |
| content_type | varchar |
content_id is the primary key for this table.
Kids_content is an enum that takes one of the values ('Y', 'N') where:
"Y! means is content for kids otherwise 'N' is not content for kids.
content_type is the category of the content as movies, series, etc.
Write an SQL query to report the distinct titles of the kid-friendly movies streamed in
June 2020.
Return the result table in any order.The query result format is in the following example.
ter
TVProgran table:
| progran_date | content_id | channel |
| 220-06-10 e8:08 =| 4 | Lc-channel |
| 2020-05-11 12:08 | 2 | Lc-channel |
| 2@20-@5-12 12:08 | 3 | Lc-channel |
| 2020-05-13 14:08 | 4 | Disney ch |
| 2¢20-6-18 14:08 | 4 | Disney ch |
| 2020-07-15 16:08 | 5 | Disney ch |
Content table:
| content_id | title | Kids_content | content_type |
la | Leetcode Movie | N | Movies |
12 | Alg. for Kids | Y | series |
13 | Database Sols | N | Series |
|4 | Aladdin ly | Movies |
1s | Cinderella | Y | Movies |
| Aladdin |
“Leetcode Novie” is not a content for kids.
“Alg. for Kids" is not 2 movie.
“patabase Sols" is not a movie
“Alladin” is a movie, content for kids and was streamed in June 2020.
"Cinderella" was not streamed in June 2020.Solution
SELCT DISTINCT title
FROM
(SELCT content_Ad, title
FROM content
WHERE kids content = 'Y' AND content_type = 'Movies’) a
JOIN
‘tvprogram USING (content_id)
WHERE month(program_date) = 6
1501. Countries You Can Safely Invest In | Medium | ( LeetCode
| Colunn are | Type — |
| i [int |
| name | varchar |
| phone_number | varchar |
id is the primary key for this table.
Each row of this table contains the name of a person and their phone number.
Phone number will be in the form "xxx-yyyyyyy" where xxx is the country code (3 ¢
—— JYaSX—rS——>
Table country:
| Column Name | Type |
| name | varchar |
| country_code | varchar |country_code is the primary key for this table.
Each row of this table contains the country name and its code. country_code will
—,
Table calls:
| Column Name | Type |
| callerid | int |
| calleeid | int |
| duration | int |
There is no primary key for this table, it may contain duplicates.
Each row of this table contains the caller id, callee id and the duration of the
A teleconmunications company wants to invest in new countries. The country intend
————————————
Write an SQL query to find the countries where this company can invest.
Return the result table in any order.
The query result format is in the following example.
Person table:
| id | name | phone_number |
| 3. | Jonathan | @51-1234567 |
[12 | elvis | 051-7654321 |
[1 | Moncet | 212-1234567 |
[2 | Maroua | 212-6523651 |
17 | Meir | 972-1234567 |
[9 | Rachel | 972-0011100 |Country table:
| country_code |
| Peru | @52
|
| Israel | 972 |
| Morocco | 212 \
| Germany | @49 |
| Ethiopia | 251 |
calls table
| caller_id | callee_id | duration |
ja 19 | 33 I
12 13 14 |
1a 12 | 59 |
13 | 12 | 182 1
13 | 12 | 330 |
| 12 13 15 |
\7 lo [33 |
17 12 13 |
lo 17 fa |
fa 17 17 |
Result table:
| country |
The average call duration for Peru is (102 + 162 + 330 + 330+ 5 +5) / 6 = 145.6
The average call duration for Israel is (3344413413 4341+4147)/8
The average call duration for Morocco is (33 + 4 + 59 +59 +347) / 6 = 27.5000
Global call duration average = (2 * (33 + 3459 + 102433045 433434247
Since Peru is the only country where average call duration is greater than the gl
|Solution
WITH ta AS(
SELECT caller_id AS id, duration AS total
FROM
(SELECT caller_id, duration
FROM calls
UNION ALL
SELECT callee_id, duration
FROM calls) a
d
SELECT name AS country
FROM
(SELECT distinct avg(totel) OVER(PARTITION BY code) AS avg_call, avg(total) OVER(
FROM
(SELECT *, coalesce(total,@) AS duration, SUBSTRING(phone_number FROM 1 for 3) A
FROM person RIGHT JOIN t1
USING (id) b
join country ¢
ON c.country_code = b.code)) d
WHERE avg_call > global_avg
1511. Customer Order Frequency | Easy | @ LeetCode
Table: customers
| Colum Name | Type |
| customer_id | int |
| name | varchar |
| country | varchar |
customer_id is the primary key for this table.
This table contains information of the customers in the company.Table: product
| column Nare | Type |
| product_id | int |
| description | varchar |
| price faint |
product_id is the primary key for this table.
This table contains information of the products in the company.
price is the product cost.
Table: orders
| column Name | Type |
| order_id [ant |
| customer_id | int |
| productid | int |
| order_date | date |
| quantity [int |
order_id is the primary key for this table.
This table contains information on customer orders.
customer_id is the id of the customer who bought “quantity” products with id "pro
Order_date is the date in format (‘YYYY-M4-DD") when the order was shipped.
—
Write an SQL query to report the customerid and customername of customers who
have spent at least $100 in each month of June and July 2020.
Return the result table in any order.