2021.10.6 开始刷Database-MySQL,小白刷题,争取每天打卡记录。
175. Combine Two Tables [E]
Write an SQL query to report the first name, last name, city, and state of each person in the Person
table. If the address of a PersonId
is not present in the Address
table, report null
instead.
select p.FirstName, p.LastName,a.City, a.State
from Person p
left join Address a on p.PersonId = a.PersonId;
176. Second Highest Salary [M]
Write an SQL query to report the second highest salary from the Employee
table. If there is no second highest salary, the query should report null
.
*选第二大的,就是选比最大的小的
select max(salary) as SecondHighestSalary from Employee
where salary<(select max(salary) from Employee);
177. Nth Highest Salary [M]
Write an SQL query to report the nth
highest salary from the Employee
table. If there is no nth
highest salary, the query should report null
.
*选第N大的,可以用offst的用法
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE num INT;
SET num=N-1;
RETURN (
SELECT(SELECT DISTINCT Salary
FROM Employee ORDER BY Salary DESC
LIMIT num,1)AS getNthHighestSalary
);
END
178. Rank Scores [M]
Write an SQL query to rank the scores. The ranking should be calculated according to the following rules:
Return the result table ordered by score
in descending order
*dense rank用法:DENSE_RANK ( ) OVER ( [
也可 统计比该score大的个数+1作为rank
**rank作为名字要加上引号,防止歧义
select s.Score,
(select count(distinct s1.Score)+1 from Scores s1
where s1.Score > s.Score) 'rank'
from Scores s
order by s.Score desc
180. Consecutive Numbers [M]
Write an SQL query to find all numbers that appear at least three times consecutively.
*通过self copy进行限制
select distinct l1.Num as ConsecutiveNums
from Logs l1, Logs l2, Logs l3
where (l1.Num=l2.Num and l2.Num=l3.Num and l1.Num = l3.Num)
AND (l2.Id = l1.Id + 1) AND (l3.Id = l2.Id + 1)
181. Employees Earning More Than Their Managers [E]
Write an SQL query to find the employees who earn more than their managers.
select e.Name as Employee
from Employee e, Employee e1
where e.ManagerId = e1.Id and e.Salary > e1.Salary
182. Duplicate Emails [E]
Write an SQL query to report all the duplicate emails.
SELECT Email from Person GROUP BY Email HAVING COUNT(*) > 1;
183. Customers Who Never Order [E]
Write an SQL query to report all customers who never order anything.
*需要用Id做筛选,而不是名字,因为名字会重复
select cc.Name as Customers from Customers cc
where cc.Id not in
(select c.Id from Customers c
inner join Orders o on o.CustomerId = c.Id)
184. Department Highest Salary [M]
Write an SQL query to find employees who have the highest salary in each of the departments.
select d.Name as 'Department', e.Name as Employee, e.Salary from Employee e
left join Department d on d.Id=e.DepartmentId
where e.Salary = (select max(ee.Salary) from Employee ee where ee.DepartmentId=e.DepartmentId)
185. Department Top Three Salaries [H]
A company's executives are interested in seeing who earns the most money in each of the company's departments. A high earner in a department is an employee who has a salary in the top three unique salaries for that department.
Write an SQL query to find the employees who are high earners in each of the departments.
*主要难在count()<3
select d.Name as 'Department', e.Name as Employee, e.Salary
from Employee as e
join Department as d
on e.DepartmentId = d.Id
where (
(select count(distinct e2.Salary)
from Employee as e2
where e2.Salary > e.Salary and e.DepartmentId=e2.DepartmentId)
<3);
196. Delete Duplicate Emails [E]
Write an SQL query to delete all the duplicate emails, keeping only one unique email with the smallest Id
.
*delete 用法
DELETE FROM Person
WHERE Id NOT IN (SELECT id FROM (SELECT Email, MIN(Id) AS 'id' FROM Person GROUP BY Email) t)
197. Rising Temperature [E]
Write an SQL query to find all dates' Id
with higher temperatures compared to its previous dates (yesterday).
*注意记得date时间转化
select w1.Id from Weather w1
inner join Weather w
on w.Temperature < w1.Temperature and DATE(w1.RecordDate) = DATE(w.RecordDate + INTERVAL 1 DAY)
262. Trips and Users [H]
Write a SQL query to find the cancellation rate of requests with unbanned users (both client and driver must not be banned) each day between "2013-10-01"
and "2013-10-03"
.
The cancellation rate is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.
Return the result table in any order. Round Cancellation Rate
to two decimal points.
*很多小细节注意一下,如round到2位,时间限制,tricky的地方是通过0,1判断计算cancel state
select s.Day, round(sum(s.status)/count(s.Id),2) as 'Cancellation Rate' from
(select t1.Request_at as Day, t1.Id,
(select if(t2.Status like 'cancelled%',1,0) from Trips t2
where t2.Id=t1.Id) as 'status'
from Trips t1
inner join Users u
inner join Users u1
on t1.Client_Id=u.Users_Id and t1.Driver_Id=u1.Users_Id
where u.Banned = 'No' and u1.Banned= 'No' and (t1.Request_at >= '2013-10-01' and t1.Request_at <= '2013-10-03')
order by t1.Request_at) s
group by s.Day
511. Game Play Analysis I [E]
Write an SQL query to report the first login date for each player.
*记得改column的名字呀!
select distinct player_id, min(event_date) as first_login from Activity
group by player_id
512. Game Play Analysis II [E]
Write an SQL query to report the device that is first logged in for each player.
*看着简单,其实挺难搞,要注意同时使(player_id,event_date)满足要求
select player_id,device_id
from activity
where (player_id,event_date)
in (select player_id,min(event_date) as event_date from activity group by 1)
534. Game Play Analysis III [M]
Write an SQL query to report for each player and date, how many games played so far by the player. That is, the total number of games played by the player until that date. Check the example for clarity.
*太慢了,不好
select a.player_id, a.event_date,
(select sum(a1.games_played) from Activity a1
where a1.player_id=a.player_id and a.event_date>=a1.event_date) as 'games_played_so_far'
from Activity a
*学会新技能,partition by!
select a.player_id, a.event_date,
sum(a.games_played) over (partition by a.player_id order by a.event_date asc) as 'games_played_so_far'
from Activity a
550. Game Play Analysis IV [M]
Write an SQL query to report the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.
select round(count(distinct ss.id)/(select count(distinct player_id) from Activity),2) as 'fraction'
from
(select a.player_id as id
from Activity a
inner join
(select player_id,min(event_date) as min_date from Activity
group by player_id) s
on a.player_id = s.player_id and s.min_date+1=a.event_date) ss
569. Median Employee Salary [H]
Write an SQL query to find the median salary of each company.
Return the result table in any order.
select s.id, s.company, s.salary
from
(select id, company, salary,
ROW_NUMBER() OVER (PARTITION BY company ORDER BY salary asc) AS num
from Employee) s,
(select company,count(distinct id) as total from Employee
group by company) s1
where s.company=s1.company and s.num in (s1.total/2, s1.total/2+1, s1.total/2+0.5)
570. Managers with at Least 5 Direct Reports [M]
Write an SQL query to report the managers with at least five direct reports.
select distinct e.name from Employee e,
(select id, name, managerId,
count(managerId) over (partition by managerId) as total
from Employee) s
where e.id=s.managerId and s.total >=5
571. Find Median Given Frequency of Numbers [H]
Write an SQL query to report the median of all the numbers in the database after decompressing the Numbers
table. Round the median to one decimal point.
*遇到复杂的题可以分window,第一个表示统计总数,第二个找到位子
With cte_1 as
(Select
*,
sum(Frequency) over() as total_freq,
sum(Frequency) over(order by num) as end_freq
from Numbers
),
cte2 as(
Select
*,
case when total_freq%2=0 then total_freq/2 end as mid_1,
case when total_freq%2=0 then (total_freq/2)+1 end as mid_2,
case when total_freq%2=1 then round((total_freq/2)+0.5) end as mid_3,
lag(end_freq,1,0) over (order by num) as start_freq
from cte_1
)
Select avg(num) as median from cte2
where (mid_1 > start_freq and mid_1<=end_freq)
or (mid_2 > start_freq and mid_2<=end_freq)
or (mid_3 > start_freq and mid_3<=end_freq)
574. Winning Candidate [M]
Write an SQL query to report the name of the winning candidate (i.e., the candidate who got the largest number of votes).
*简写小技巧:group by 1就是第一列排序;count(*)就是返回所有行数(包括null),count(列名)不计入null
SELECT name
FROM Candidate
WHERE id = (SELECT candidateId
FROM Vote
GROUP BY 1
ORDER BY COUNT(*) DESC LIMIT 1)
577. Employee Bonus[E]
Write an SQL query to report the name and bonus amount of each employee with a bonus less than 1000
.
*注意is NULL和=NULL是不一样的
select e.name, b.bonus
from Employee e
left join Bonus b
on e.empId = b.empId
where b.bonus < 1000 or b.bonus is NULL
578. Get Highest Answer Rate Question [M]
Write an SQL query to report the question that has the highest answer rate. If multiple questions have the same maximum answer rate, report the question with the smallest question_id
.
select ss.question_id as survey_log from
(select s.question_id, s.num_answer, s.num_question, s.num_answer/s.num_question as rate
from
(select id, question_id, answer_id,
count(answer_id) over (partition by question_id) as num_answer,
count(question_id) over (partition by question_id) as num_question
from SurveyLog) s
where s.answer_id is not NULL
order by s.num_answer/s.num_question desc, s.question_id asc
limit 1) ss
579. Find Cumulative Salary of an Employee [H]
Write an SQL query to calculate the cumulative salary summary for every employee in a single unified table.
*写了一坨大大的屎山,先去掉最大的month,在通过case when写加和形式
with c1 as
(select e.id, e.month, e.salary
from Employee e,
(select id,max(month) as max_mon from Employee
group by id) e1
where e.id = e1.id and e.month c13.month+1) then
c11.salary+c12.salary
when c11.month<>c12.month+1 then c11.salary
end as Salary
from c1 c11, c1 c12, c1 c13
where c11.id=c12.id and c11.id=c13.id
order by c11.id asc, c11.month desc) s
group by s.id, s.month
order by s.id asc, s.month desc
*原来可以用ifnull感觉世界突然明亮了
SELECT a.id, a.month,
a.salary + IFNULL(b.salary, 0) + IFNULL(c.salary, 0) AS Salary
FROM Employee a
LEFT JOIN Employee b ON a.id = b.id AND a.month = b.month + 1
LEFT JOIN Employee c ON a.id = c.id AND a.month = c.month + 2
JOIN (SELECT id, MAX(month) AS last_month FROM Employee GROUP BY id) d ON a.id = d.id
WHERE a.month != d.last_month
ORDER BY a.id, a.month DESC
580. Count Student Number in Departments [M]
Write an SQL query to report the respective department name and number of students majoring in each department for all departments in the Department
table (even ones with no current students).Return the result table ordered by student_number
in descending order. In case of a tie, order them by dept_name
alphabetically.
*point72刚考过
select d.dept_name, count(s.student_id) as student_number
from Department d
left join Student s
on d.dept_id=s.dept_id
group by d.dept_id
order by student_number desc, d.dept_name asc
584. Find Customer Referee [E]
Write an SQL query to report the IDs of the customer that are not referred by the customer with id = 2
.
*注意 <>2是不包含等于Null的值的,所以要单独判断Null
select name from Customer
where referee_id<>2 or referee_id is Null
585. Investments in 2016 [M]
Write an SQL query to report the sum of all total investment values in 2016 tiv_2016
, for all policyholders who:
tiv_2015
value as one or more other policyholders, andlat, lon
) attribute pairs must be unique).Round tiv_2016
to two decimal places.
select round(sum(i.tiv_2016),2) as 'tiv_2016' from Insurance i
where i.tiv_2015 in
(select distinct tiv_2015 from
(select pid,tiv_2015,tiv_2016,
count(tiv_2015) over (partition by tiv_2015 order by tiv_2016 asc) as 2015_num
from Insurance) s
where s.2015_num > 1)
and
concat(i.lat,i.lon) in
(select concat(lat,lon) as loc from Insurance
group by concat(lat,lon)
having count(concat(lat,lon))=1)
586. Customer Placing the Largest Number of Orders [E]
Write an SQL query to find the customer_number
for the customer who has placed the largest number of orders. The test cases are generated so that exactly one customer will have placed more orders than any other customer.
select s.customer_number from
(select customer_number,
count(order_number) over (partition by customer_number) as total from Orders) s
order by s.total desc
limit 1
595. Big Countries [E]
A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million. Write a SQL solution to output big countries' name, population and area.
select name, population, area from World
where area > 3000000 or population>25000000
596. Classes More Than 5 Students [E]
Please list out all classes which have more than or equal to 5 students.
*没事还是加上distinct吧,坑很多
select class from courses
group by class
having count(distinct student)>=5
597. Friend Requests I: Overall Acceptance Rate [E]
Write an SQL query to find the overall acceptance rate of requests, which is the number of acceptance divided by the number of requests. Return the answer rounded to 2 decimals places.
*注意Null的用法
with table1 as (select round((select count(distinct requester_id, accepter_id) from RequestAccepted) / (select count(distinct sender_id, send_to_id) from FriendRequest),2) as accept_rate)
select
CASE
when accept_rate is Null then 0
else accept_rate
end
as accept_rate
from table1
601. Human Traffic of Stadium [H]
Write an SQL query to display the records with three or more rows with consecutive id
's, and the number of people is greater than or equal to 100 for each.
Return the result table ordered by visit_date
in ascending order.
*先筛选大于100的id,再判断是否连续
select distinct s3.id, s3.visit_date, s3.people
from Stadium s3,
(select s1.id from
(select * from Stadium where people >= 100) s1
where s1.id+1 in (select id from Stadium where people>=100) and s1.id+2 in (select id from Stadium where people>=100)) s2
where s3.id in (s2.id,s2.id+1,s2.id+2)
order by s3.visit_date asc
602. Friend Requests II: Who Has the Most Friends [M]
Write an SQL query to find the people who have the most friends and the most friends number.
*写了一坨屎山
with c1 as
(select requester_id, accepter_id,
count(requester_id) over (partition by requester_id order by requester_id) as re_num,
count(accepter_id) over (partition by accepter_id) as ac_num
from RequestAccepted),
req as
(select distinct requester_id, re_num from c1),
acc as
(select distinct accepter_id, ac_num from c1),
out1 as
(select distinct s.id, max(s.num) as num from
(select a.accepter_id as id,
case when a.accepter_id=r.requester_id then a.ac_num+r.re_num
when a.accepter_id <> r.requester_id then a.ac_num
end as num
from acc a, req r) s
group by s.id),
out2 as
(select o.id, o.num, r.requester_id, r.re_num
from out1 o, req r)
select
case when o2.num >= o2.re_num then o2.id
when o2.re_num > o2.num then o2.requester_id
end as id,
case when o2.num >= o2.re_num then o2.num
when o2.re_num > o2.num then o2.re_num
end as num
from out2 o2
order by num desc
limit 1
* union的用法,把两个以上的 SELECT 语句的结果组合到一个结果集合中。多个 SELECT 语句会删除重复的数据。distinct(默认),all(全部,包含重复值)
SELECT f1 as 'id', count(distinct f2) as 'num'
FROM ((SELECT requester_id as 'f1', accepter_id as 'f2'
FROM RequestAccepted)
UNION
(SELECT accepter_id as 'f1', requester_id as 'f2'
FROM RequestAccepted)) a
GROUP BY f1
ORDER BY count(distinct f2) DESC
LIMIT 1
603. Consecutive Available Seats [E]
Write an SQL query to report all the consecutive available seats in the cinema.
Return the result table ordered by seat_id
in ascending order.
with seat as
(select seat_id from Cinema
where free = 1)
select * from
((select s.seat_id
from seat s, seat s1
where s1.seat_id-s.seat_id=1)
union
(select s1.seat_id
from seat s, seat s1
where s1.seat_id-s.seat_id=1))ss
order by ss.seat_id
607. Sales Person [E]
Write an SQL query to report the names of all the salespersons who did not have any orders related to the company with the name "RED". Return the result table in any order.
select s.name from SalesPerson s
where s.sales_id not in
(select distinct o.sales_id
from Orders o
where o.com_id=
(select c.com_id from Company c where c.name='RED'))
608. Tree Node[M]
Each node in the tree can be one of three types:
Write an SQL query to report the type of each node in the tree.
Return the result table ordered by id
in ascending order.
select id,
case when p_id is null then 'Root'
when p_id is not null and (id in (select p_id from Tree)) then 'Inner'
else 'Leaf'
end as type
from Tree
610. Triangle Judgement [E]
Write an SQL query to report for every three line segments whether they can form a triangle.
select *,
case when (x+y>z) and (x+z>y) and (z+y>x) then 'Yes'
else 'No'
end as triangle
from Triangle t
612. Shortest Distance in a Plane[M]
The distance between two points p1(x1, y1)
and p2(x2, y2)
is sqrt((x2 - x1)2 + (y2 - y1)2)
.
Write an SQL query to report the shortest distance between any two points from the Point
table. Round the distance to two decimal points.
select ROUND(MIN(SQRT(power(p1.x-p.x,2) + power(p1.y-p.y,2))),2) as shortest
from Point2D p
join Point2D p1 on (p.x,p.y) != (p1.x,p1.y)
613. Shortest Distance in a Line [E]
Write an SQL query to report the shortest distance between any two points from the Point table.
with t1 as
(select ROW_NUMBER() over (order by x asc) as num, x
from Point),
t2 as
(select ROW_NUMBER() over (order by x asc) as num, x
from Point)
select min(abs(t1.x-t2.x)) as shortest from t1,t2
where t1.num+1=t2.num
614. Second Degree Follower [M]
A second-degree follower is a user who:
follows at least one user, and
is followed by at least one user.
Write an SQL query to report the second-degree users and the number of their followers.Return the result table ordered by follower
in alphabetical order.
with t1 as
(select followee, count(followee) as num from Follow
group by followee),
t2 as
(select distinct follower from Follow)
select t1.followee as follower, t1.num from t1
where t1.followee in (select * from t2)
order by t1.followee
615. Average Salary: Departments VS Company [D]
Write an SQL query to report the comparison result (higher/lower/same) of the average salary of employees in a department to the company's average salary.
*注意时间的写法
with t1 as
(select date_format(pay_date, '%Y-%m') as pay_month, avg(amount) as com_avg
from Salary
group by pay_month),
t2 as
(select date_format(s.pay_date, '%Y-%m') as pay_month,e.department_id, avg(s.amount) as de_avg
from Salary s
left join Employee e
on e.employee_id = s.employee_id
group by pay_month, e.department_id),
t3 as
(select t2.pay_month, t2.department_id, t2.de_avg, t1.com_avg
from t2
left join t1 on t1.pay_month=t2.pay_month)
select t3.pay_month, t3.department_id,
case when t3.de_avg > t3.com_avg then 'higher'
when t3.de_avg=t3.com_avg then 'same'
when t3.de_avg
618. Students Report By Geography [H]
Write an SQL query to pivot the continent column in the Student table so that each name is sorted alphabetically and displayed underneath its corresponding continent. The output headers should be America, Asia, and Europe, respectively.
*注意通过row来left join
with t1 as
(select s1.name as 'America', ROW_NUMBER() over (order by s1.name) as num
from Student s1
where s1.continent='America'),
t2 as
(select s1.name as 'Asia', ROW_NUMBER() over (order by s1.name) as num
from Student s1
where s1.continent='Asia'),
t3 as
(select s1.name as 'Europe', ROW_NUMBER() over (order by s1.name) as num
from Student s1
where s1.continent='Europe')
select s1.America,s1.Asia,t3.Europe from
(select t1.America,t2.Asia,t1.num from t1
left join t2
on t1.num=t2.num) s1
left join t3
on t3.num=s1.num
619.Biggest Single Number [E]
A single number is a number that appeared only once in the MyNumbers table. Write an SQL query to report the largest single number. If there is no single number, report null.
select max(s.num) as num from
(select num,count(num) as t from MyNumbers
group by num
having count(num) = 1) s
620. Not Boring Movies [E]
Write an SQL query to report the movies with an odd-numbered ID and a description that is not "boring"
. Return the result table in descending order by rating
.
select * from Cinema c
where c.id % 2 = 1 and c.description != 'boring'
order by c.rating desc
626. Exchange Seats [M]
Mary is a teacher in a middle school and she has a table seat
storing students' names and their corresponding seat ids. The column id is continuous increment. Mary wants to change seats for the adjacent students.
* 如果是奇数行,id+1,偶数行 id-1;但是如果总体为奇数,最后一项不变。注意 if的用法
select if(large%2=0,ss.num,if(ss.num=large+1,ss.num-1,ss.num)) as id,
ss.student
from
(select s.num, s.student,
(select max(s1.id) from seat s1) as large
from
(select if(id%2=0,id-1,id+1) as num, student from seat
order by num asc) s) ss
627. Swap Salary [E]
Write an SQL query to swap all 'f'
and 'm'
values (i.e., change all 'f'
values to 'm'
and vice versa) with a single update statement and no intermediate temp table(s).
*update可以修改值
UPDATE Salary SET
sex = if(sex='m','f','m')
1045. Customers Who Bought All Products [M]
Write an SQL query to report the customer ids from the Customer table that bought all the products in the Product table.
*数量一样
with t1 as
(select customer_id, count(distinct product_key) as num
from Customer
group by customer_id),
t2 as
(select count(distinct product_key) as total from Product)
select t1.customer_id from t1,t2
where t1.num=t2.total
1050. Actors and Directors Who Cooperated At Least Three Times [E]
Write a SQL query for a report that provides the pairs (actor_id, director_id) where the actor has cooperated with the director at least three times.
select s.actor_id,s.director_id from
(select actor_id, director_id, ROW_NUMBER() over (partition by actor_id,director_id) as num
from ActorDirector) s
where s.num >=3
group by s.actor_id,s.director_id
1068. Product Sales Analysis I [E]
Write an SQL query that reports the product_name, year, and price for each sale_id in the Sales table.
select p.product_name, s.year, s.price
from Sales s left join Product p
on p.product_id = s.product_id
1069. Product Sales Analysis II [E]
Write an SQL query that reports the total quantity sold for every product id.
select product_id, sum(quantity) as total_quantity from Sales
group by product_id
1070. Product Sales Analysis III [M]
Write an SQL query that selects the product id, year, quantity, and price for the first year of every product sold.
SELECT a.product_id, a.`year` AS `first_year`, a.`quantity`, a.`price`
FROM (
SELECT *, RANK() OVER(PARTITION BY product_id ORDER BY year) as row_num
FROM `Sales`
) AS `a`
WHERE a.`row_num` = 1
1075. Project Employee I [E]
Write an SQL query that reports the average experience years of all the employees for each project, rounded to 2 digits.
select s.project_id, round(avg(s.experience_years),2) as 'average_years' from
(select p.project_id, p.employee_id, e.experience_years
from Project p
left join Employee e
on p.employee_id=e.employee_id) s
group by s.project_id
1076. ProjectEmployees II[E]
Write an SQL query that reports all the projects that have the most employees.
select project_id from Project
group by project_id
having count(employee_id) =
(select max(s.num) from
(select count(employee_id) as num from Project
group by project_id) s)
1077. Project Employees III [M]
Write an SQL query that reports the most experienced employees in each project. In case of a tie, report all employees with the maximum number of experience years.
with t1 as
(select p.project_id, p.employee_id, e.experience_years from Project p
left join Employee e
on e.employee_id=p.employee_id),
t2 as
(select project_id, max(experience_years) as year from t1
group by project_id)
select t1.project_id,t1.employee_id
from t1,t2
where t1.project_id=t2.project_id and t1.experience_years=t2.year
1082. Sales Analysis I [E]
Write an SQL query that reports the best seller by total sales price, If there is a tie, report them all.
with t1 as
(select seller_id, sum(price) as price from Sales
group by seller_id),
t2 as
(select max(price) as max_price from t1)
select t1.seller_id from t1,t2
where t1.price=t2.max_price
1083. Sales Analysis II [E]
Write an SQL query that reports the buyers who have bought S8 but not iPhone. Note that S8 and iPhone are products present in the Product table.
with t as
(select product_id as s8 from Product
where product_name='S8'),
t0 as
(select product_id as ip from Product
where product_name='IPhone'),
t1 as
(select buyer_id from Sales
where product_id = (select * from t0)),
t2 as
(select buyer_id from Sales
where product_id = (select * from t))
select distinct t2.buyer_id
from t2
where t2.buyer_id not in (select * from t1)
1084. Sales Analysis III [E]
Write an SQL query that reports the products that were only sold in the spring of 2019. That is, between 2019-01-01 and 2019-03-31 inclusive.
with t1 as
(select product_id from Sales
where DATE(sale_date) >= DATE('2019-01-01') and DATE(sale_date) <= DATE('2019-03-31')),
t2 as
(select product_id from Sales
where DATE(sale_date) < DATE('2019-01-01') or DATE(sale_date) > DATE('2019-03-31'))
select t.product_id,p.product_name from
(select distinct t1.product_id from t1
where t1.product_id not in (select * from t2)) t
left join Product p
on p.product_id=t.product_id
1097. Game Play Analysis V [H]
The install date of a player is the first login day of that player.
We define day one retention of some date x to be the number of players whose install date is x and they logged back in on the day right after x, divided by the number of players whose install date is x, rounded to 2 decimal places.
Write an SQL query to report for each install date, the number of players that installed the game on that day, and the day one retention.
select first_date as 'install_dt', count(distinct a.player_id) as 'installs',
Round(count(distinct b.player_id)/count(distinct a.player_id), 2) as `Day1_retention`
from (
select player_id, min(event_date) as first_date from Activity group by player_id) a
left join Activity b
on a.player_id = b.player_id and DATEDIFF(b.event_date, a.first_date)=1
group by first_date
1098. Unpopular Books [M]
Write an SQL query that reports the books that have sold less than 10 copies in the last year, excluding books that have been available for less than one month from today. Assume today is 2019-06-23.
with t1 as
(select book_id from Orders where DATE(dispatch_date) >DATE('2018-06-23')
group by book_id
having sum(quantity)>=10)
select o.book_id,b.name from
(select o.book_id from Books o where o.book_id not in (select * from t1)) o
left join Books b
on b.book_id=o.book_id
where DATE(b.available_from+INTERVAL 1 MONTH)
1179. Reformat Department Table [E]
Write an SQL query to reformat the table such that there is a department id column and a revenue column for each month.
select id,
max(if(month="Jan", revenue, null)) as Jan_Revenue,
max(if(month="Feb", revenue, null)) as Feb_Revenue,
max(if(month="Mar", revenue, null)) as Mar_Revenue,
max(if(month="Apr", revenue, null)) as Apr_Revenue,
max(if(month="May", revenue, null)) as May_Revenue,
max(if(month="Jun", revenue, null)) as Jun_Revenue,
max(if(month="Jul", revenue, null)) as Jul_Revenue,
max(if(month="Aug", revenue, null)) as Aug_Revenue,
max(if(month="Sep", revenue, null)) as Sep_Revenue,
max(if(month="Oct", revenue, null)) as Oct_Revenue,
max(if(month="Nov", revenue, null)) as Nov_Revenue,
max(if(month="Dec", revenue, null)) as Dec_Revenue
from Department
group by id