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

Database Questions

Uploaded by

DURAISAMY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
32 views

Database Questions

Uploaded by

DURAISAMY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 106
Database Questions Database Questions = 175. Combine Two Tables = 176. Second Highest Salary = 177. Nth Highest Salary = 178. Rank Scores = 180. Consecutive Numbers = 181, Employees Eaming More Than ‘Their Managers = 182, Duplicate Emails = 183, Customers Who Never Order = 196, Delete Duplicate Emails = 197. Rising Temperature = Stl. Game Play Analysis I = 512. Game Play Analysis IT = 534. Game Play Analysis IIT = 570. Managers with at Feast 5 Direct Reports + 577. Employce Bonus = 584, Find Customer Referee = 586, Customer Placing the Largest Number of Orders, = 595, Big Countries = 596, Classes More Than 5 Students = 597. Prien Requests I: Overall Acceptance Rate = 603. Consecutive Available Seats = 607. Sales Person = 618. Tree Node = 610. Triangle Judgement = 612. Shortest Distance in a Plane = 613. Shortest Distance in a Line = 619. Biggest Single Number = 620. Not Boring Movies = 626. Exchange Seats = 627. Swap Salary = 1045. Customers Who Bought Alll Products = 1050. Actors and Directors Who Cooperated At Least Three Times = 1068, Product Sales Analysis | = 1069, Product Sales Analysis IL = 1070. Product Sales Analysis III = 1075. Project Employees I = 1076, Project Employees Il = 1077. Project Employees Ill = 1082. Sales Analysis 1 = 1083. Sales Analysis Il = 1084, Sales Analysis IIT = 1112, Highest Grade For Each Student = 1113. Reported Posts = 1126. Active Businesses TIAL. User Activity for the Past 30 Days I = 1142, User Activity for the Past 30 Days II = T148, Article Views I = 1164. Product Price ata Given Date = 1173. Immediate Food Delivery I = 1174, Immediate Food Delivery I = 1179. Reformat Depastment Table = 1193, Monthly Transactions T = 1204. Last Person to Fit in the Elevator = 1211. Queries Quality and Perentage = 1212. Team Scores in Football ‘Tournament = 1225, Report Contiguous Mates = 1241, Number of Comments per Post = 1251, Average Selling Price = 1264, Page Recommendations = 1270. All People Report to the Given Manager #1280. Students and Fxaminations #1285, Find the Start and End Number of Continuous Ranges = 1294, Weather Type in Fach Country = 1303.Find the Team Size = 1308, Running Total for Different Genders = 1321, Restaurant Growth = 1322, Ads Performance = 1327. List the Products Ordered in a Period = 1336, Number of Transactions per Visit 175. Combine Two Tables Description Table: Person | Persontd int | | FirstName | varchar | | LastName | varchar | PersonId is the primary key column for this table. Table: Address | Column Name | Type | | AddressId | int | | Persontd | int | | city | varchar | | State | varchar | AddressId is the primary key colunn for this table. Write @ SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people: FirstName, LastName, City, State Solution 01/02/2020; # Write your MySOL query statenent below select FirstNane, LastName, City, State from Person as p left join Address as a on p.PersonId = a.PersonId; 176. Second Highest Salary Description Write a SQL query to get the second highest salary from the Employee table. | Id | Salary | For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return qull. | SeconcHighestSalary | | 200 Solution 01/13/2020: # Write your MySQL query statenent below select ifnull(( select distinct Salary from Employee order by Salary dese Limit 1 offset 1), nut) as SecondHighestSalary; 177. Nth Highest Salary Description Write a SQL query to get the nth highest salary from the Employee table. | Id | Salary | For example, given the above Employee table, the nth highest salary where n = 2 1s 200. If there 1s no nth highest salary, then the query should return null. + | getNthHighestSalary(2) boded Solution 01/13/2020: CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT BEGIN declare M INT; setM=N-1; RETURN ( # Write your MySQL query statement below. select distinct Salary from Employee order by Salary desc limit 1 offset M END 178. Rank Scores Description Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking nunber should be the next consecutive integer value. In other words, there should be no "holes" between ranks. a | Id | Score | + i | | | | 4.00 | I ' | 1 1 1 2 3 4 5 6 | I | I | | + For example, given the above Scores table, your query should generate the following report (order by highest score): + | Score | Rank | 14.00 | | 4.00 | 13.85 | 13.65 | Solution 01/21 /2020 (MS SQLServer): /* Write your T-SQL query statement below +/ select Score, dense_rank() over(order by Score desc) as Rank from Scores; 01/21 /2020 (MySQL, Variables): # Write your MySQL query statenent below select Score, @rank © from Scores, (select @rank : order by Score desc; @rank + (@prev <> (@prev := Score)) as Rank 2, @prev := -1) as a 01/21/2020 (MySQL, count): # Write your MySQL query statement below select Score, (select count(distinct Score) from Scores where Score >= s.Score) as Rank from Scores as s order by Score desc; 180. Consecutive Numbers Description Write @ SQL query to find all oumbers that appear at least three times consecutively. | Id | Num | a [2 13 14 Is For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times. a | ConsecutiveNums | | ca Solution 01/21/2020 (MySQL, user defined variables): # Write your MySQL query statenent below select distinct Num as ConsecutiveNums from ( select Num, @cnt := if(@prev = (@prev := Num), @cnt + 1, 1) as freq from Logs, (select @cnt := 0, @prev := (select Num from Logs Limit 1)) as c dasn where freq > 2; 181. Employees Earning More Than Their Managers Description The Employee table holds all employees including their managers. Every employee has en Id, and there is also a column for the manager Id. | Id | Name | Salary | ManagerId | 11 | Joe | 70000 | 3 12 | Henry | 80000 | 4 13 | Sam | 60000 | NI 14 [Nt | Nax | 90000 Given the Enployee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager. | Employee | Joe pe eel Solution 01/18/2020: # Write your MySQL query statenent below select e.Nane as Employee from Employee as e inner join Employee as m on e.NanagerId = m.id where e.Salary > m.Salary; 182. Duplicate Emails Description Write a SOL query to find all duplicate emails in a table named Person. | Id | Emait | + + | [email protected] | | [email protected] | | [email protected] | + + | [email protected] | Note: All enails are in lowercase. Solution 01/18/2020: # Write your MySQL query statenent below select Email from Person group by Email having count (Email) > 1; 183. Customers Who Never Order Description Suppose that a website contains two tables, the Customers table and the Orders table. Write a SOL query to find all customers who never order anything. Table: Customers. | Joe | | Henry | | Sam | [Max | Solution 01/18/2020: # Write your MySQL query statenent below select Name as Customers from Customers where Id not in ( select Custonerid from Orders i 196. Delete Duplicate Emails Deseription Write a SQL query to delete all duplicate enail entries in a table named Person, keeping only unique emails based on its smallest Id. | Id | Emait 1 1 | johngexample.com | 2 | bobeexanple-com | 3 | johngexample.com | | I ! + Id is the primary key colum for this table. For example, after running your query, the above Person table should have the following rows: | Id | Emait I | 1 | johngexampte.com | 1.2 | [email protected] | Your output is the whole Person table after executing your sql. Use delete statement. Solution 01/18/2020: # Write your MySOL query statenent below delete pot from Person as p, ( select Email, min(Id) as mintd from Person group by Email having count(*) > 1 dasq where p.Email = q.m2il and 1d > q.minid; 01/18/2020: # Write your MySOL query statenent below delete pl from Person as pl, Person as p2 where pl.Enail = p2.Enall and pi.td > p2.1 197. Rising Temperature Description Given a Weather table, write a SQL query to find all dates’ Ids with higher ‘temperature compared to its previous (yesterday's) dates. = = + | Id(INT) | RecordDate(DATE) | Tenperature(INT) | I 11 2015-01-01 | 10 | | 21 2015-01-02 | 2 | I 31 2015-01-03 | 20 | | 4 2015-01-04 | 30 | For example, return the following Ids for the above Weather table: Solution 01/18/2020; # Write your MySOL query statenent below select w1.Id from Weather as wi, Weather as w2 where datediff(wi1.RecordDate, w2.RecordDate) = 1 and wi.Temperature > w2. Temperature; 511. Game Play Analysis I Description Table: Activity | Column Name | Type | playerid | int | deviceid = | int | event_date | date | ganes_played | int (player_id, event_date) is the primary key of this table. This table shows the activity of players of sone game. Each row is a record of a player who logged in and played a nunber of ganes (possibly @) before logging out on some day using some device. Write an SQL query that reports the first login date for each player. ‘The query result format is in the following example: Activity table: + | player_id | device_id | event_date | games_played | 11 12 | 2016-03-01 | 5 | ja 12 | 2016-05-02 | 6 | 12 13 | 2017-06-25 | 1 | 13 ha | 2016-03-02 | @ | 13 14 | 2018-07-03 | 5 | Result table: | player_id | first_login | ja | 2016-03-01 | 12 | 2017-06-25 | 13 | 2016-03-02 | Solution 01/13/2020: # Write your MySQL query statenent below select player_id, min(event date) as first_login from Activity group by player_id order by player_ic 512. Game Play Analysis II Description Table: activity a | Column Name | Type | a | pleyerid | int | | deviceid | int | | event_date | date | | games_played | int | = + (player_id, event_date) is the primary key of this table. This table shows the activity of players of sone game. Each row is a record of a player who logged in and played a nunber of ganes (possibly @) before logging out on some day using some device. Write a SQL query that reports the device that is first logged in for each player. The query result format is in the following example: Activity table: | player_id | device_id | event_date | games_played | [a 12 | 2016-03-01 | 5 jl | 2016-05-02 | 2017-06-25 | 2016-03-02 | 2018-07-03 16 | 12 | le | 15 | Solution 01/18/2020: # Write your MySQL query statement below select player_id, device_id from Activity where (player_id, event_date) in ( select player_id, min(event_date) from Activity group by player_id % 534. Game Play Analysis III Description Table: Activity | Column Name | | playerid | | deviceid | | event_date | | games_played | (player_id, event_date) is the primary key of this table. This table shows the activity of players of sone game. Each row is a record of a player who logged in and played a nunber of games (possibly ) before logging out on some day using sone device. Write an SQL query that reports 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. The query result format is in the following example: Activity table: + a + | player_id | device_id | event_date | games_played | [a 12 | 2016-03-01 | 5 | [a 12 | 2016-05-02 | 6 | a 13 | 2017-06-25 | 1 | 13 fa | 2016-03-02 | @ | 13 14 | 2018-07-03 | 5 | - a | 2016-03-01 | 5 I ba | 2026-95-02 | 12 | ja | 2017-06-25 | 12 | 13 | 2016-03-02 | 9 | 13 | 2018-07-03 | 5 | For the player with id 1, 5 + 6 = 11 games played by 2016-05-02, and 5 +6 +1= 12 games played by 2017-06-25. For the player with id 3, 0 + 5 = 5 games played by 2018-07-03. Note that for each player we only care about the days when the player logged in. Solution 01/21 /2020 (MySQL): # write your MySQL query statement below select player_id, event_date, games_played_so_far from ( select player_id, event_date, if(@player = (eplayer := player_id) and @nydate < (@nydate := event_date), games := @games + games_played, (@games := ganes_played) ) 8s games_played_so_far, Gnydate from (select * from Activity order by player_id, event_date) as a, ‘ select @player := (select player_id from Activity order by player_id, event_date Limit 1), Q@mydate := (select event_date from Activity order by player_id, event_date Limit 1), @games := (select games_played from Activity order by player_id, event_date Limit 1) ) as tmp das te event_date 01/21/2029 (MySQl.) # Write your MySQL query statenent below select player_id, event_date, games_played_so_far trom ( select player_id, event_date, G@ganes := if(player_id = @player, @games + ganes_played, games_played) as games_played_so_far, @layer i= player_id from (select * from Activity order by player_id, event_date) as a, (select @player := -1, @games := 0) as tmp das ty 570. Managers with at Least 5 Direct Reports Description The Employee table holds all employees including their managers. Every employee has en Id, and there is also @ column for the manager Id. [Id [Name Department |ManagerId | [101 [John JA Inuit | [102 [Dan JA [e2 | [103 [James JA }101 | [104 jamy JA lien | [105 JAnne JA lo | [196 [Ron |B [101 I = = Given the Enployee table, write a SQL query that finds out managers with at least 5 direct report. For the above table, your SQL query should return: Note: No one would report to himself. Solution 01/21 /2020 (MySQL): # Write your MySQL query statenent below select Name from Employee where Id in ( select ManagerId from Employee group by Managerid having count(+) >= 5 % 577. Employee Bonus Description Select all employee's name and bonus whose bonus is < 1000. Table: Employee ‘5 | empId | name | supervisor] salary | 12 [| gonn | 3 | 1000 | 12 [dan | 3 | 2000 | | 3 | Brad | mutt =| 4000 | | 4 | Thomas | 3 | 4000 | enpId is the primary key colum for this table. Table: Bonus | empId | bonus | 12 | 500 | 14 | 2000 | a enpIé is the primary key colum for this table. Example ouput: | name | bonus | [ohn | mutt | [pan | 500 | | Bred | mutt | Solution 01/14/2020; # Write your MySQL query statenent below select name, bonus from Employee as e left join Bonus as b on e.empId = b.enpId where bonus < 1000 or bonus is null; 584. Find Customer Referee Description Given a table customer holding customers information and the referee. | id | name | referee_id| 1a yp win | NULL | | 2 | Jane | NULL | 13 | Alex | 21 | 4 peu y NULL | | 5 | Zack | 11 | 6 | Mark | 21 Write a query to return the List of customers NOT referred by the person with id "2 For the sample data above, the result is: wit Bill | | | Jane | | | | Zack | 4 Solution 01/14/2020, # Write your MySQL query statenent below select name from customer where referee_id is null or referee_id = 586. Customer Placing the Largest Number of Orders Description Query the customer_number from the orders table for the customer who has placed ‘the largest nunber of orders. It is guaranteed that exactly one customer will have placed more orders than any other custoner. The orders table is defined as follows: | Cotumn int int | | | | | order_number (PK) | \ customer_number — | \ order_date | date | | | | | | | | Il | | | required_date date | shipped_date date | status char(15) | conment char (200) Sample Input | order_number | customer_number | order_date | required_date | shipped_date | status | conment | ha | 2017-04-09 | 2017-04-13 | 2017-04-12 | Closed | 12 | 2017-04-15 | 2017-04-20 | 2017-04-18 | Closed | 13 | 2017-04-16 | 2017-04-25 | 2017-04-20 | Closed | [4 | 2017-94-18 | 2017-04-28 | 2017-04-25 | Closed | Sample Output | customer_number | I- “| 13 | Explanation ‘The customer with number '3' has two orders, which is greater than either customer '1' or '2' because each of them only has one order. So the result is customer_number '3'. Follow up: what if more than one customer have the Largest number of orders, can you find all the customer_number in this casc? lution 01/14/2020; # Write your MySOL query statement below select customer_number from ( select customer_nunber, count (+) as cnt trom orders group by customer_number dase order by e.cnt desc Limit 1; 595. Big Countries Description There is a table World | nane | continent | ares | population | gdp | Afghanistan | Asia | 652230 | 25500100 © |, 20343000 | Albania | Europe | 28748 | 2831741 | 12960000 | Algeria | Africa | 2381741 | 37100000 ©— | 188681000 | Andorra | Europe | 468 | 78115 | 3712000 | Angola | Africa | 124670 | 20609204 © |__ 100990000 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. For example, according to the above table, we should output: | population | Afghanistan | 25500100 | 652230 I | Algeria | 371¢00@0 = | 2381741 I Solution 01/13/2020: # Write your MySQL query statement below select name, population, area from World where area >= 3000000 or population >= 25000000; 596. Classes More Than 5 Students Description There is a table courses with columns: student and class Please list out all classes which have more than or equal to 5 students. For example, the table: | student | class A | Math B | English | Math | Biology | math | Computer | Math | Math | Hzommoo Math Should output: Note: The students should not be counted duplicate in each course. Solution 01/18/2020: # Write your MySQL query statement below select class from courses group by class having count (distinct student) >= 5; 597. Friend Requests I: Overall Acceptance Rate Description In social network Like Facebook or Twitter, people send friend requests and accept others’ requests as well. Now given two tables as below: Table: friend_request | sender_id | send_to_id | request_date| Is =| | 2016_06-01 | | 2016_06-01 | | 2016_06-01 | | 2016_06-02 | 13 14 | 2016-06-09 | Table: request_accepted requester_id | accepter_id laccept_date zi I- | 2016_e6-03 | 2016-06-08 | 2016-06-08 | 2016-06-09 | 2016-06-10 1 2 1 3 2 3 3 4 3 4 Write a query to find the overall acceptance rate of requests rounded to 2 decinals, which is the number of acceptance divide the number of requests. For the sample data above, your query should return the following result. laccept_rate| Note: The accepted requests are not necessarily from the table friend_request. In this case, you just need to simply count the total accepted requests (no matter whether they are in the original requests), and divide it by the number of requests to get the acceptance rate. It is possible that @ sender sends multiple requests to the sane receiver, and a request could be accepted more than once. In this case, the ‘duplicated’ requests or acceptances are only counted once. If there is no requests at all, you should return 0.00 as the accept_rate. Explanation: There are 4 unique accepted requests, and there are 5 requests in total. So the rate is 0.80. Follow-up: Can you write a query to return the accept rate but for every month? How about the cumulative accept rate for every day? Solution 01/18/2020: # Write your MySQL query statenent below select round(if(requests = 9, 0, accepts / requests), 2) as accept_rate from ( select count (distinct sender_id, send_to_id) as requests from friend_request dasry, ( select count (distinct requester_id, accepter_id) as accepts from request_accepted ) as a; 603. Consecutive Available Seats Description Several friends at a cinema ticket office would like to reserve consecutive available seats. Can you help to query all the consecutive available seats order by the seat_id using the following cinema table? | seat_id | free | Note: The seat_id is an auto increment int, and free is bool ('1' means free, and ‘0! means occupied. ). Consecutive available seats are more than 2(inclusive) seats consecutively available. Solution 01/18/2020: # Write your MySQL query statenent below select distinct cl.seat_id from cinema as cl join cinena as ¢2 join cinema as c3 on cl.seat_id = c2.seat_id +1 || Cleseat_id = c3.seat_id - 1 where cl.free = 1 and c2.free = 1 and c3.free 01/18/2020: # Write your MySQL query statement below select distinct c?.seat_id from cinema as cl, cinema as c2 where cl. free = 1 and c2.free = 1 and cl.seat_id = c2.seat_id + 1 union select distinct cl.seat_id from cinema as cl, cinema as c2 where cl.free = 1 and c2.free = 1 and cl.seat_id = c2.seat_id + 1 order by seat_i 607. Sales Person Description Description Given three tables: salesperson, company, orders. Output all the nanes in the table salesperson, who didn’t have sales to company "RED". Example Input Table: salesperson | sales_id | hire_cate | 11 | John | 100000 | 6 | 4/1/2006 | 12 | Any | 120000 | 5 | 5/1/2010 | 13 | Mark | 65000 2 | 12/25/2008 | 14 | Pam | 25000 | = 25 11/1/2005 | 1s | Alex | 5e0ee | 10 | 2/3/2007 | The table salesperson holds the salesperson infornation. Every salesperson has a sales_id and a name. company _ | comic | name | city = | + 11 | RED | Boston | | 2 | ORANGE |New York | | 3 | YELLOW | Boston | | 4 | GREEN | Austin | + + + The table company holds the company information. Every company has a com_id and a nane. Table: orders | order_id | order_date | comid | sales_id | amount | 1a | at2ea4} 3 | 4 | 100000 | 12 | 22a} 4 | 5 | 5000 | 13 | 3/24} 1 | 61 | 50000 | 14 | ama} 1 | 4 | 25000 | a The table orders holds the sales record information, salesperson and customer company are represented by sales_id and com_id. output I | | + Explenation According to order '3' and '4' in table orders, it is easy to tell only salesperson ‘John’ and ‘Alex' have sales to conpany 'RED', 50 we need to output all the other names in table salesperson. Solution 01/14/2020; # Write your MySQL query statenent below select s.nane from salesperson as s where s.sales_id not in( select sales_id from orders as o left join company as c on o.comid = c.con_id where c.nane = 'RED') 608. Tree Node Deseription Given a table tree, id is identifier of the tree node and p_id is its parent node's id. Each node in the tree can be one of three types: Leaf: if the node is a leaf node. Root: if the node is the root of the tree. Inner: If the node is neither a leaf node nor a root node. Write a query to print the node id and the type of the node. Sort your output by ‘the node id. The result for the above sample i: id | Type | Root | Inner | Leaf | Leaf | 1] 2) 3 | Leaf | 4) 5 | Explanation Node '1' is root node, because its parent node is NULL and it has child node '2' and '3'. Node '2' is inner node, because it has parent node '1' and child node '4" and cate Node '3', '4' and ‘5! is Leaf node, because they have parent node and they don't have child node. And here is the inage of the sample tree as below: Note If there is only one node on the tree, you only need to output its root attributes. Solution 01/22/2020; # Write your MySOL query statenent below select id, case when p_id is null then ‘Root! when pid is not null and id in (select distinct pid fron tree) then ‘Inner’ else ‘Leaf' end as Type from tree; 610. Triangle Judgement Description A pupil Tim gets homework to identify whether three line segments could possibly form a triangle. However, this assignment is very heavy because there are hundreds of records to calculate. Coulé you help Tim by writing a query to judge whether these three sides can form a triangle, assuming table triangle holds the length of the three sides x, y and 2. | 13 | 15 | 30] | 10 | 20 | 45 | For the sample data above, your query should return the follow result: Ix |y [2 | triangle | II =I [13 | 15 | 30 | No I | 10 | 20 | 15 | Yes I ution 01/14/2020; # Write your MySQL query statement below select x, y, 2, case when x+y >zandx +z>y and y+z>x then ‘Yes’ clse ‘Not end as triangle from triangle ; 612. Shortest Distance in a Plane Description Table point_2d holds the coordinates (x,y) of some unique points (more than two) in a plane. Write a query to find the shortest distance between these points rounded to 2 decinals. The shortest distance is 1.00 from point (-1,-1) to (-1,2). So the output should be: | shortest | Note: The longest distance among all the points are less than 10000. Solution 01/22/2020. # Write your MySQL query statenent below select round(min(dist), 2) as shortest from ( select if(a.x = b.x and a.y = b.y, 10000, sqrt(power(a.x - b.x, 2) + powerla.y = by, 2))) as dist from point_2d as a, point_2d as b das dj 613. Shortest Distance in a Line Description Table point holds the x coordinate of sone points on x-axis in a plane, which are all integers. Write a query to find the shortest distance between two points in these points. The shortest distance is '1' obviously, which is from point '-1' to '0'. So the output 1s as below: | shortest] Note: Every point is unique, which means there is no duplicates in table point. Follow-up: what if all these points have an id and are arranged from the left most to the right most of x axis? Solution 01/13/2020. # Write your MySQL query statenent below select min(abs(a.x ~ b.x)) as shortest from point as a, point as b where a.x I= b.x; 619. Biggest Single Number Description Table my_numbers contains many numbers in colunn num including duplicated ones. Can you write a SQL query to find the biggest number, which only appears once. + num | URE wWUwe 6! For the sample data above, your query should return the following result: ot |num| le} Note: If there is no such number, just output null. Solution 01/18/2020, # Write your MySQL query statenent below select max(num) as num from ( select nun from my_numbers group by num having count(nun) = 1 das nz 620. Not Boring Movies Description X city opened a new cinema, many people would Like to go to this cinema. The cinena also gives out a poster indicating the movies’ ratings and descriptions. Please write a SOL query to output movies with an odd nunbered ID and a description that is not ‘boring’. Order the result by rating. For example, table cinema: | id | movie | description | rating | 12 | War | great 30 | 8.9 | | 2 | Science | fiction | 8.5 = | | 3 | arish | borang | 2 | 4 | Ice song | Fantacy | 8.6 = | | 5 | House card] Interesting] 9.1 | | id | movie | description | rating | — | 5 | House card] —Interesting| 1a | War | great 30 | Solution 01/14/2020: # Write your MySQL query statenent below select id, movie, description, rating from cinema where id % 2 = 1 and description < ‘boring’ order by rating desc; 626. Exchange Seats Description 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 scats for the adjacent students. Can you write a SQL query to output the result for Mary? | student - | Abbot | Doris | Emerson | Green | Jeames For the sample input, the output is: 5 | 5 | | | | I | id | student | ~ + | 1 | Doris | | 2 | Abbot | | 3 | Green | | 4 | Emerson | 1 5 | Jeames | + + Note: If the number of students is odd, there is no need to change the last one's seat Solution 01/22/2020: # Write your MySQL query statenent below select if(mod(id, 2) = 0, id ~ 1, if(id < (select max(id) from seat), id + 1, id)) as id, student from seat order by id; 627. Swap Salary Description Given a table salary, such as the one below, that has mnale and f=female values. 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. Note that you must write a single update statenent, D0 NOT write any select statement for this problem. Example: id | name | sex | salary I | zee | | I | I Hr }a qm f 12 18 [Ff | 150e 13 1C 1m | 5500 14 [0 |f | 500 | After running your update statement, the above salary table should have the following rows: | id | name | sex | salary | [1 [A [Ff | 250 | 12 18 |[m | 150 | 13 1c [tf | 550 | 14 [0 [m | 500 | Solution 01/13/2020: # Write your MySQL query statenent below # update salary # set sex = case when sex else 'm' end; update salary set sex = if(sex = 'm', 'f', 'm'); 1045. Customers Who Bought All Products Description Table: Customer | Column Name | Type | | custoner_id | int | | product_key | int | = te Product_key is a foreign key to Product table. Table: Product | product_key | int | product_key is the primary key column tor this table. Write an SQL query for a resort that provides the customer ids from the Customer table that bought all the products in the Product table. For example: Customer table: | customer_id | product_key Product table: | product_key | The customers who bought all the products (5 and 6) are customers with id 1 and 3. Solution 01/21/2020 (MySQL) # Write your MySQL query statenent below select customer_id from Customer group by custoner_id having sum(distinct product_key) = ( select sun(product_key) from Product i 1050. Actors and Directors Who Cooperated At Least Three Times Description Table: ActorDirector + | Column Nane | Type | Fe | actorid | int | | director_id | int | | timestamp | int =| + + ‘timestamp is the primary key colunn for this table. Write a SQL query for a report that provides the pairs (actor_id, director_id) where the actor have cooperated with the director at least 3 times. Example: ActorDirector table: ree —— | actor_id | director_id | timestamp | ha 1a lo I {2 [2 ih | 12 12 12 1 a 12 13 I [4 12 14 ' |2 {2 15 | |2 12 16 | + + Result table: + | actor_id | director_id | The only pair is (1, 1) where they cooperated exactly 3 times. Solution 01/13/2020: # Write your MySQL query statenent below # select actor_id, director_id # from ( # select actor_id, director_id, count(*) as cnt # from ActorDirector # group by actor_id, director_id # having cnt >= 3) as e; select actor_id, director_id from ActorDirector group by actor_id, director_id having count (*) >= 3; 1068. Product Sales Analysis I Description Table: Sales toe ponecnaot | Column Name | Type | + |saleid = | int | | product_id | ant | | year [ant | I quantity | int | | price | int | fa (sale_id, year) is the primary key of this table. product_id is a foreign key to Product table. Note that the price is per unit. Table: Product | Column Nane | Type | = | product_id | int | | product_name | varchar | Product_id is the primary key of this table. Write an SQL query that reports all product names of the products in the Sates table along with their selling year and price. For example: Sales table: | sale_id | product_id | year | quantity | price | la | 100 | 2008 | 10 | 5000 | 12 | 100 | 2009 | 12 | 5000 | 17 | 200 | 211 | 45 | 9000 | | product_id | product_name | | 100 | Nokia | | 200 | Apple | | 300 | Sansung | | product_name | year | price | | Nokia | 2008 | 5000 | | Nokia | 2009 | 5000 | | Apple | 2011 | 9000 | Solution 01/13/2020, # Write your MySOL query statenent below select distinct P.product_name, S.year, S.price from (select distinct product_id, year, price from Sales) inner join Product as P using (product_id) ; 1069. Product Sales Analysis II Description Table: Sales | Column Nane | Type | [saleid | int | | product_id | int | | year | int | | quantity | int | | price [ant | sale_id is the primary key of this table. product_id is a foreign key to Product table. Note that the price is per unit. Table: Product | Column Name | Type | product_id | int | product_name | varchar + product_id is the primary key of this table. 7 Il i I Fa Write an SQL query that reports the total quantity sold for every product id. ‘The query result format is in the following example: Sales table: = = ha | 100 | 2008 | 10 | 5000 | 12 | 100 | 2009 | 12 | 5000 | 17 | 200 | 2011 | 15 | 9000 | = | product_id | product_name | | 100 | Nokia | | 200 | Apple | | 300 | Sansung | Result table: es | product_id | totat_ouantity | | | | 108 | 22 | 200 [15 Solution 01/13/2020, # Write your MySQL query statenent below select product_id, sum(quantity) as total_quantity from Sales group by product_id; 1070. Product Sales Analysis III Description Table: sales | Column Name | Type | | saleid = | int | | product_id | int | | year | int | [quantity | int | | price [ant | sale_id is the primary key of this table. product_id is a foreign key to Product table. Note that the price is per unit. Table: Product | Column Nane | Type | product_id | int | product_name | varchar | 5 i fl product_id is the primary key of this table. Write an SQL query that selects the product id, year, quantity, and price for the first year of every product sold. The query result format is in the following example: Sales table: + = + | sale_id | product_id | year | quantity | price | | 100 | 2008 | 10 | 5000 | | 100 | 2009 | 12 | 5000 | | 200 | 2011 | 15 | 9000 | Product table: + + | product_id | product_name | | 100 | Nokia 1 | 200 | Appte I | 300 | Samsung I Result table: + + | product_id | first_year | quantity | price | | 2008 110 | seeo | | 2011 Solution 01/22/2020; select product_id, year as first_year, quantity, price from Sales where (product_id, year) in (select product_id, min(year) as year from Sales group by product_id); 1075. Project Employees I Description Table: Project | Column Name | Type | | project_id | int | | employee_id | int | a (project_id, enployee_id) is the primary key of this table. enployee_id is a foreign key to Enployee table. Table: Employee ra | Cotumn Name I Type | employee_id | [int | | name | varchar | | experience_years | int I enployee_id is the primary key of this table. Write an SQL query that reports the average experience years of all the enployees for each project, rounded to 2 digits. The query result format is in the following example | project_id | enployee_id BRUNE | employee_id | name | experience_years | |1 | Khaled | 3 1 12 | Ali 12 1 13 | John | 2 1 14 | Doe | 2 1 Result table: = | project_id | average_years ha | 2.00 12 | 2.50 The average experience years for the first project is (3 +2 +1) / 3 = 2.00 and for the second project is (3 +2) / 2 = 2.50 Solution 01/14/2020; # Write your MySQL query statement below select project_id, round(avg(experience_years), 2) as averaye_years from Project as p left join Employee as © on p.employee_id = e.employee_id group by project_id; 1076. Project Employees II Description Table: Project | Column Name | Type | | project_id | int | | employee_id | int | + + (project_id, employee_id) is the primary key of this table. enployee_id is a foreign key to Employee table. Table: Employee | Column Name Type | | employee_id [ant | | name | varchar | | | experience_years + enployee_id is the primary key of this table. int I —+ Write an SQL query that reports all the projects that have the most employees. The query result format is in the following example: Project table: enployee_id | + project_id | employee_id | name ha | Khaled | 12 jai | 13 | John | 14 | Doe | + The first project has 3 employees while the second one has 2. Solution 01/18/2020; # Write your MySQL query statement below select project_id from Project group by project_id having count (employee_id) >= ( select count(employee_1d) as cnt from Project Group by project_id order by cnt desc Linit 1 v4 1077. Project Employees III Description Table: Project | Column Name | Type | | project_id | int | | employee_id | int | (project_id, enployee_id) is the prinary key of this table. enployee_id is a foreign key to Enployee table. Table: Employee | Column Name I Type | employee_id | ant I | | nane | varchar | | experience years | int ! enployee_id is the primary key of this table. 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. The query result format is in the following example: Project tabi | project_id | employee_id RHUNE Enployee table: | employee_id | name | experience_years | = + a | Khaled | 3 1 Result table: a | project_id | employee_id a | | i | | | | Both employees with id 1 and 3 have the most experience among the employees of the first project. For the second project, the employee with id 1 has the most experience. Solution 01/19/2020 (MySQL) # Write your MySQL query statement below select p.project_id, e-employee_id from ( select project_id, max(experience_years) as max_years from Project as p join Employee as e on p-employee_id = e.employee_id group by project_id ) as a, Project as p, Employee as ¢ where p.project_id = q.project_id and p.employee_id = e.employee_id and max_years; e-experience_years 01/19/2020 (MySQL) # Write your MySOL query statenent below select p.project_id, e.employee_id from Project as p, Employee as € where p.employee_id = e.employee_id and (p.project_id, e.experience_years) in | select project_id, max(experience_years) as experience_years from Project as p join Employee as e on p.employee_id = e,employee_id Group by project_id ) 1082. Sales Analysis I Description Table: Product | Column Nane | Type | ay | productid | int = | | product_name | varchar | | unit_price | int | a + Product_id is the primary key of this table. Table: Sales | Column Nane | Type | |sellerid | int | | product_id | int | | buyerid | int | | saleate | date | | quantity | int | | price [int | This table has no primary key, it can have repeated rows. product_id is a foreign key to Product table. Write an SQL query that reports the best seller by total sales price, If there is a tie, report them all. The query result format is in the following example: Product table: product_id | product_name | unit_price | 1 Ise | 1000 \ 2 | Ga | 800 \ 3 | iPhone | 1400 | : | seller_id | product_id | buyer_id | sale date | quantity | price | " ja 1 a | 2019-01-21 | 2 | 2000 | ia 12 12 | 2019-92-17 | 1 1300 | 12 12 13 | 2019-96-02 | 1 | 800 | 13 13 14 | 2019-95-13 | 2 | 280¢ | | | ca Both sellers with id 1 and 3 sold products with the most total price of 2800. Solution 01/13/2020: # Write your MySQL query statement below select seller_id from Sales group by seller_id having sum(price) >= ( select sun(price) a5 total_price from Sales group by seller_id order by total_price desc lami 1)5 # select seller_id # from Sales # group by seller_id # having sun(price) >= all( # select sum(price) # from Sales # group by seller_id #); 1083. Sales Analysis II Description Table: Product | Column Nane | Type | + | product_id | int | | product_name | varchar | | unit_price | int | + ra + product_id is the primary key of this table. Table: Sales | Column Nane | Type | | setlerid | int | | product_id | int | | buyerid | int =| | saleate | date | | quantity | int | | price ant | This table has no primary key, it can have repeated rows. product_id is a foreign key to Product table. Write an SOL query that reports the buyers who have bought 58 but not iPhone. Note that S8 and iPhone are products present in the Product table. The query result format is in the following example: Product table: es | product_id | product_name | unit_price | Is | 1000 I 11 [2 | Ga | 800 \ 13 | iphone | 1400 | Sales table: | seller_id | product_id | buyer_id | sale_date | quantity | price | + la [a fa | 2019-01-21 | 2 | 2008 | [a [2 12 | 2019-02-17 | 1 | 800 | 12 ha 13 | 2019-06-02 | 1 1800 | 13 13 13 | 2019-05-13 | 2 | 2800 | + The buyer with id 1 bought an SB but didn't buy an iPhone. The buyer with id 3 bought both. Solution 01/18/2020: # Write your MySQL query statement below select distinct s.buyer_id from Sales as s join Product as p on s.product_id = p.product_id where product_name = 'S8' and s-buycr_id not in ( select buyer_id from Sales as s join Product as p on s.product_id = p.product_id where product_name = ‘iPhone! dM 01/18/2020; # Write your MySQL query statenent below select buyer_id from Sales join Product using(product_id) group by buyer_id having sum(product_name = 'S8') > @ and sum(product_name = 'iPhone') 1084. Sales Analysis III Description Table: Product 2 | Column Name | Type | | product_id | int | | product_name | varchar | | unit_price | int | product_id is the primary key of this table. Table: Sales Column Nane | Type | | int product_id | int buyerid | int sale_date | date quantity | int price | int re ! | setler_id | | | | | Fe — This table has no primary key, it can have repeated rows. product_id is a foreign key to Product table. Write an SQL query that reports the products that were only sold in spring 2019. That is, between 2019-01-01 and 2019-03-31 inclusive. The query result format is in the following example: Product table: | product_id | product_name | unit_price | + [a | se | 1000 | 12 | 64 | 800 \ 13 | iPhone | 1400 | + | seller_id | product_id | buyer id | sale date | quantity | price | es 1a i et | 2019-01-21 | 2 | 2000 | ia 12 [2 | 2019-92-17 | 1 | 800 | 12 12 13 | 2019-06-02 | 1 | 800 | 13 13 14 | 2019-05-13 | 2 | 2800 | Result table: | product_id | product_name | The product with id 1 was only sold in spring 2019 while the other two were sold after. Solution 01/18/2020, select product_id, product_name from Sales inner join product using(product_id) group by product_id having sum(if(sale_date between '2019-01-01' and '2019-03-31', 1, 0)) = sum(if(sale_date, 1, 0)): 1112. Highest Grade For Each Student Description Table: Enrollments | Column Name | Type | | student_id | int | | courseid = | int | | grade jint | (student_id, course_id) is the primary key of this table. Write a SQL query to find the highest grade with its corresponding course for each student. In case of a tie, you should find the course with the smallest course_id. The output must be sorted by increasing student_id. The query result format is in the following example: Enrollments table: | student_id | course_id | grade | 95, + | 95 | .@ | 99 | se | 3% | i 82 Result table: ne | student_id | course_id | grade | 01/21/2020 (MySQL): # Write your MySQL query statement below select student_id, min(course_id) as course_id, grade from Enrollments where (student_id, grade) in ( sclect student_id, max(gradc) from Enrollments group by student_id ) group by student_id order by student_id asc; 1113. Reported Posts Description Table: Actions | Column Nane | Type | | user_id | int I | post_id | int I | actiondate | date | | action [enum | | extra | varchar | There is no primary key for this table, it may have duplicate rows. The action column is an ENUM type of (‘view', ‘Like’, 'reaction', comment", ‘report’, ‘share'). The extra column has optional information about the ection such as a reason for report or a type of reaction. Write an SQL query that reports the number of posts reported yesterday for each report reason. Assume today is 2019-07-05. The query result format is in the following example: Actions table: | user_id | post_id | action_date | action | extra | + + ha 11 | 2019-97-01 | view | mutt | ha 11 | 2619-97-01 | like | null | 1 11 | 2¢19-07-01 | share | mutt | 12 14 | 2e19-07-04 | view | null | [2 14 | 2019-97-04 | report | spam | 13 14 | 2019-07-04 | view | mutt | 13 14 | 2019-97-04 | report | spam | l4 13 | 2¢19-07-02 | view | null | 14 13 | 2019-07-02 | report | spam | 15 12 | 2019-07-04 | view | null | Is 12 | 2019-97-04 | report | racism | 15 15 | 2019-07-04 | view | mutt | 15 15 | 2019-07-04 | report | racism | 5 Note that we only care about report reasons with non zero number of reports. Solution 01/14/2020: # Write your MySQL query statenent below select extra as report_reason, count(x) as report_count from ( select post_id, extra from Actions where action_date = '2019-07-04' and action = ‘report" group by post_id, extra) as t group by t-extra 01/14/2020: # Write your MySQL query statenent below select extra as report_reason, count(distinct post_id) as report_count from Actions where action_date = '2019-07-04' and action = ‘report' group by extra; 1126. Active Businesses Description Table: events — + | Column Nane | Type | to + | business_id | int | | event_type | varchar | J occurences | int | ra (business_id, event_type) 1s the primary key of this table. Each row in the table logs the info that an event of some type occured at some business for a nunber of times. Write an SQL query to find all active businesses. An active business is a business that has more than one event type with occurences greater than the average occurences of that event type among all businesses. The query result format is in the following example: Events table: | business_id | event_type | occurences | ha | reviews | 7 i 13 | reviews | 3 i et | ads lu I 12 | ads 17 I 13 | ads 16 I a | page views | 3 I 12 | page views | 12 i tads' and ‘page views' are (7#3)/2=5, (11+7+6)/3-8, Average for ‘reviews', (3#12) /2=7.5 respectively. Business with id 1 has 7 ‘reviews’ events (more than 5) and 11 ‘ads’ events (nore than 8) so it is an active business. Solution 01/21 /2020: # Write your MySOL query statenent below select business_id from Events e, ( select event_type, avg(occurences) as avg_occurences trom Events group by event_type dasa where e.event_type = a.event_type and e.occurences > a.avg_occurences group by e.business_id having count (*) > 1; 1141. User Activity for the Past 30 Days I Description Table: Activity | Column Nane | Type | user_id fant | sessionid | int | activity date | date | activity_type | enum | ! | | | ra + + There is no primary key for this table, it may have duplicate rows. The activity_type column is an ENUM of type (‘open_session', ‘end_session', *scroll_down', ‘send message"). The table shows the user activities for a social media website. Note that each session belongs to exactly one user. Write an SQL query to find the daily active user count for a period of 30 days ending 2019-07-27 inclusively. A user was active on some day if he/she made at least one activity on that day. The query result format is in the following example: Activity table: session_id | activity_date | activity_type 2019-07-20 open_session 2019-07-20 scrolt_down 2019-07-20 end_session 2019-07-20 open_session 2019-07-21 send_nessage Tu unnnnaunautat | | \ \ \ | | | | | | 2019-07-21 | end_session | \ | \ | | | | | | 2019-07-21 open_session 2019-07-21 send_nessage 2019-07-21 end_session 2019-06-25 open_session 2019-06-25 end_session | 2019-07-20 | 2 I | 2019-07-21 | 2 I co Note that we do not care about days with zero active users. Solution 01/18/2020: # Write your MySQL query statenent below select activity_date as day, count(distinct user_id) as active_users from Activity where activity_date between '2019-06-28" and '2019-07-27' group by day; 1142. User Activity for the Past 30 Days II Description Table: Activity Column Name | Type | user_id | ant I session_id | int I activity_date | date | activity type | enum 1 + | Es | I | | + There is no primary key for this table, it may have duplicate rows. The ectivity_type column is an ENUM of type (‘open_session', ‘end_session', *scroll_down', 'send_message'). The table shows the user activities for a social media website. Note that each session belongs to exactly one user. Write an SOL query to find the average number of sessions per user for a period of 30 days ending 2019-07-27 inclusively, rounded to 2 decinal places. The sessions we want to count for a user are those with at least one activity in that time period. The query result format is in the following example: Activity table: | user_id | session_id | activity date | activity type — | + 11 1a | 2019-07-20 | open_session | ia a | 2019-07-20 | scrolt_down | a 1a | 2019-07-20 | end_session | 12 14 | 2019-07-20 | open_session | 12 14 | 2019-07-21 | send_nessage | 12 14 | 2019-07-21 | end_session | 13 12 | 2019-07-21 | open_session | 13 12 | 2019-07-21 | send_message | 13 12 | 2019-07-21 | end_session | 13 15 | 2019-07-21 | open_session | 13 15 | 2019-07-21 | scroULdown | 13 15 | 2019-07-21 | end_session | 14 13 | 2019-06-25 | open_session | 14 13 | 2019-06-25 | end_session | + + Result table: | average_sessions_per_user | User 1 and 2 each had 1 session in the past 30 days while user 3 had 2 sessions so the average is (1+ 1+ 2) / 3= 1.33. Solution 01/18/2020: # Write your MySQL query statement below select round(ifnull(sum(sessions) / count(user_id), 0), 2) as average_sessions_per_user from ( select distinct user_id, count (distinct session_id) as sessions from Activity where activity date between '2019-@6-28' and '2019-07-27' group by user_i¢ having count(+) == 1 das uy 1148. Article Views I Description Table: Views | Colum Nane | Type | Jarticleid | int | | authorid = | int | | viewerid = | int | | viewdate | date | There is no primary key for this table, it may have duplicate rows. Each row of this table indicates that some viewer viewed an article (written by some author) on some date. Note thet equal author_id and viewer_id indicate the same person. Write an SQL query to find all the authors that viewed at least one of their own articles, sorted in ascending order by their id. The query result format is in the following example: Views table: | article_id | author_id | viewer_id | viewdate | | 2019-08-01 | | 2019-08-02 | | 2019-08-01 | | 2019-08-02 | | i | i ! i 2019-07-22 2019-07-21 2019-07-21 wWeNNen BaVVNUY Solution 01/13/2020; # Write your MySQL query statenent below select distinct author_id as id from Views where author_id order by author_id; iewer_id 1164. Product Price at a Given Date Description Table: Products | Column Name product_id | | new_price | change_date | Type | int | int | date (product_id, change_date) is the prinary key of this table. Each row of this table indicates that the price of some product was changed to a new price at some date. Write an SQL query to find the prices of all products on 2019-08-16. Assume the price of all products before any change is 10. The query result format is in the following example: Products table: | product_id | new_price | change_date | [a | 20 | 2019-08-14 | 12 | 50 | 2019-08-14 | ha | 30 | 2019-08-15 | a 135 | 2019-08-16 | 12 | 65 | 2019-08-17 | 13 | 20 | 2019-08-18 | | product_id | price | Solution 01/22/2020: # Write your MySQL query statenent below select L.product_id, max(if(i.product_id not in (select product_id from Products where change_date <= date '2019-08-16' group by product_id), 10, (select new_price from Products where product_id = i.product_id and product_id = q.product_id and change_date = q.max_change_date])) as price from (select distinct product_id fron Products) as i, ( select product_id, max(change_date) as max_change_date trom Products where change_date <- date '2019-08-16" ‘group by product_id )asaq group by i-product_id; 1173. Immediate Food Delivery I Description Table: Delivery | Column Name | Type | delivery_id | int | customer_id | aint | order_date | date | customer_pref_delivery_date | date | + — delivery_id 1s the primary key of this table. The table holds information about food delivery to customers that make orders at some date and specify a preferred delivery date (on the same order date or after it). If the preferred delivery date of the custoner is the same as the order date ‘then the order is called immediate otherwise it's called scheduled. Write an SQL query to tind the percentage of inmediate orders in the table, rounded to 2 decinal places. The query result format is in the following example: Delivery table: | delivery_id | customer_id | order_date | customer_pref_delivery_date | + a [1 | 2019-08-01 | 2019-08-02 I 2 15 | 2019-08-02 | 2019-08-02 I 2 ja | 2019-08-11 | 2019-08-11 1 4 13 | 2019-08-24 | 2019-08-26 1 5 \4 | 2019-08-21 | 2019-08-22 I 6 |2 | 2019-08-11 | 2019-08-13 I + Result table: + + | imnediate_percentage | The orders with delivery id 2 and 3 are immediate while the others are scheduled. Solution 01/13/2020: # Write your MySQL query statenent below # sclect round( # (select count\+*) from Delivery where order_date = customer_pref_delivery_date) / # (select count|+) from Delivery) * 100, # 2) 25 immediate_percentage; select round( sum(case when order_date = customer_pref_delivery_date then 1 else @ end) / count (delivery_id) * 100 » 2) as immediate_percentage from Delivery; 1174. Immediate Food Delivery II Description Table: Delivery | Column Name | Type | delivery_id int | customer_id int | | | order_date | date | customer_pref_delivery_date | delivery_id is the primary key of this table. The table holds information about food delivery to customers that make orders at some date and specify a preferred delivery date (on the same order date or after it). If the preferred delivery date of the custoner is the sane as the order date ‘then the order is called imnediate 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 inmediate 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 [1 | 2019-08-01 | 2019-08-02 I 12 \2 | 2019-08-02 | 2019-00-02 1 13 a | 2019-08-11 | 2019-08-12 1 14 13 | 2019-08-24 | 2019-08-24 1 15 13 | 2019-08-21 | 2019-08-22 I 16 12 | 2019-08-11 | 2019-08-13 1 17 [4 | 2019-08-09 | 2019-08-09 1 + ‘i | a 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 01/22/2020; # Write your MySQL query statenent below select round(sum(if(order_date = customer_pref_delivery date, 1, @)) / count(+) * 100, 2) as inmediate_percentage from Delivery where (customer_id, order_date) in ( select custoner_id, min(order_date) from Delivery group by customer_id ) 1179. Reformat Department Table Description Table: Department | Column Name | Type | | ad | ant I | revenue | int I | month | varchar | (id, month) is the primary key of this table. The table has information about the revenue of each department per month. The month has values in [*Jan", "Feb", "Har", "Apr", "May", "Jun" "Jul" , "Aug", "Sep", ct, "Nov", "Dec" Write an SOL query to reformat the table such that there is a department id colunn and a revenue column for each month. The query result format is in the following example: Department table: | id | revenue | month | 11 | 8000 | Jan | 12 [9000 | Jan | 13 | 10000 | Feb | }1 | 7000 | Feb | }2 | 6000 | mar | + + | id | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue | 11 | 8000 | 7000 | 6000 [eee | nut I 12 | 9000 | mutt | mutt [eee Putt I 13 [nu | 10000 [mute [eee Putt 1 Note that the result table has 13 columns (1 for the departnent id + 12 for the months). Solution 01/13/2020; # Write your MySQL query statenent below # select # id, # sum(case when month = 'Jan' then revenue else null end) as Jan_Revenue, # sum(case when month = ‘Feb’ then revenue else null end) as Fet_Revenue, # sum(case when month = ‘Mar’ then revenue else null end) as Mar_Revenue, # — sum(case when month = ‘Apr’ then revenue else null end) as Apr_Revenue, # sum(case when month = ‘May’ then revenue else null end) as May_Revenue, # sum(case when month = ‘Jun’ then revenue else null end) as Jun_Revenue, # sum(case when month = ‘Jul! then revenue else null end) as Jut_Revenue, # sum(case wnen month = ‘Aug’ then revenue else null end) as Aug_Revenue, # sum(case when month = *Sep' then revenue else null end) as Sep_Revenue, # sum(case when month = ‘Oct’ then revenue else null end) as Oct Revenue, # sum(case when month = 'Nov' then revenue else null end) as Nov_Revenue, # sum(case when month = ‘Dec’ then revenue else null end) as Dec_Revenue # from Department # group by id; select 3d, sun(if(month = ‘Jan‘, revenue, nult)) as Jan_Revenve, sun(if(month = "Feb", revenue, null) as Feb Revenve, sun(if(month = 'Mar', revenue, null)) as Mar_Revenue, sun(if(month = 'Apr', revenue, null) as Apr Revenue, sun(if(month = 'May', revenue, null) as May Revenue, sum(if(month = ‘Jun', revenue, null)) as Jun_Revenve, sun(if(month = "Jul, revenue, null) as Jul_Revenve, sum(if(month = ‘Aug', revenue, nult)) as Aug Revenve, sun(if(month = 'Sep', revenue, null)) as Sep Revenue, sun(1f(month = 'Oct', revenue, nuLl)) as Oct_Revenve, sun(if(month = 'Nov', revenue, null) as Nov_Revenue, sun(if(month = 'Dec', revenue, null) as Dec Revenue from Department group by id; 1193. Monthly Transactions I Description Table: Transactions | Column Name | Type | | id jant | | country | varchar | | state | enum | | amount Jint | | trensdate | 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 anount, the nunber of approved transactions and ‘their total amount. The query result format is in the following example: Transactions table: - + | id | country | state | amount | trans_date | | 121 | us | approved | 1000 | 2018-12-18 | | 122 | us | declined | 2000 | 2018-12-19 | | 123 | us | approved | 2000 | 2019-01-01 | | 124 | DE | approved | 2000 | 2019-01-07 | Result table: | month | country | trans_count | approved_count | trans_total_amount | approved_total_amount | | 2018-12 | US 12 11 | 3000 | 1000 | | 2019-01 | us a 11 | 2000 | 2000 | | 2019-e1 | DE Ja 11 | 2000 | 2000 Solution (01/21 /2020 (MySQI # Write your MySOL query statement below select date_format(trans_date, 'sY-%m') as month, country, count (*) as trans_count, sun(if(state="approved", 1, 8)) as approved_count, sun(amount) as trans_total_anount, sun(if(state='approved', amount, 0)) as approved_total_amount from Transactions group by datc_fornat(trans_date, ‘Y-Am'), country; 1204. Last Person to Fit in the Elevator Description Table: Queue | Column Nane | Type | | personid | int | | person_nane | varchar | | weight int | | 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 colunns will contain all numbers fron 1 ton, where n is ‘the number of rows in the table. 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 | 25@ | 1 13 | John Adams |350 2 16 | Thonas Jefferson | 400 | 3 12 | Will Johnliams | 200 | 4 14 | Thonas Jefferson | 175 | 5 la | James Elephant | 500 | 6 eee Result table ~ | person_nane | 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 6) will enter the elevator as their weight sum is 250 + 350 + 400 = 1000. ‘Thomas Jefferson(id 6) is the last person to fit in the elevator because he has the last turn in these three people. Solution 01/21 /2020 (MySQL) # Write your MySQL query statement below select person_name from ( select person_name, @total_weight := @totalweight + weight as total_weight from Queve, (select @total_weight := 0) as tmp order by turn dast where total_weight <= 1000 order by total_weight desc Limit 1; # Write your MySQL query statenent below select ql.person_name from Queue as qi join Queue as q2 on qi.turn >= q2.turn group by ql.turn having sum(q2.weight) <= 1000 order by sun(q2.weight) desc Umit 1; 1211. Queries Quality and Percentage Description Table: Queries | Column Name | Type | | query_nane | varchar | [result | varchar | | position | int | [rating faint | = + There is no primary key for this table, it may have duplicate rows. This table contains information collected from sone queries on a database. The position colunn 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 poor query. 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 tabl | query_name | result | position | rating | + | Dog | Golden Retriever | 1 15 I | Dog | German Shepherd | 2 1s 1 | Doo | Mute | 200 11 1 | Cat | Shirazi 15 12 1 | Cat | Siamese 13 13 I | cat | Sphynx \7 14 1 Result table: es | query_name | quality | poor_query_percentage | | | rs Dog queries quality is ((5 / 1) + (5 / 2) + (1/ 200)) / 3 = 2.50 Dog queries poor_ query_percentage is (1 / 3) * 100 = 33,33 Cat queries quality equels ((2 / 5) + (3/3) + (4/7)) / 3 = 0.66 Cat queries poor_ query_percentage is (1 / 3) * 100 = 33.33 Solution 01/14/2020: # Write your MySQL query statenent below select q.query_nane, round(ifnull(avg(rating / position), 0), 2) as quality, round( ifnult(cnt / count(q.rating) * 100, @), 2) as poor_query_percentage from Queries as q left join ( select query_name, count (*) as ent from Queries where rating < 3 group by query_name ) as p on q-query_name = p.query_nane group by q-query_name; 01/14/2020; # Write your MySQL query statement below select query_name, round(avg(rating / position), 2) as quality, round(avg(if(rating < 3, 1, 0)) * 10¢, 2) as poor_query_percentage from Queries group by query_nane; 1212. Team Scores in Football Tournament Description Table: Teams | Column Nane | Type | | team_ad | ant | | teom_name | varcher | ~ + ‘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 ant | | host_team = | int | | guest_tean | int | | host_goals | int | | guest_goats | ant | + + match_id is the primary key of this table. Each row 1s a record of a finished match between two different teams. Teams host_tean and guest_team are represented by their IDs in the teams table (tean_id) and they scored host_goals and guest_goals goals respectively. You would like to compute the scores of all teams after all matches. Points are avarded as follows: A team receives three points if they win a natch (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). A team receives no points if they lose a match (Score less goals than the opponent team). Write an SQL query that selects the team_id, team_name and num_points of each team in the tournament after all described matches. Result table should be ordered by num_points (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 | tean_name — | | 10 | Leetcode FC | | 20 | NewYork FC | | 30 | Atlanta FC | | 40 | Chicago FC | | 50 | Toronto FC | Matches table: e | matchid | host_team | guest_team | host_goals | guest_goals | 1 13 le 2 12 12 3 15 ba a ia le 5 ia lo fe | I ! ! | Fa Result tabi | teamid | teamname —|_num_points | 10 | Leetcode FC | 7 | 20 [ NewYork FC | 3 I | 50 | Toronto FC | 3 I | 30 [atlanta FO | 1 1 | 40 | Chicago FC | 0 1 4 Solution 01/19/2020 (MySQL): # Write your MySQL query statenent below select t.team_id, team_name, ifnull(numpoints, 0) as nun_points from Teams as t left join ( select teamid, sum(numpoints) as num_points trom ‘ select host_team as team_id, sum(case when host_goals > guest_goats then 3 when host_goals = guest_goals then 1 else 0 end) as num_points fron Matches Group by host_team union alt select guest_team as tean_id, sum(case when nost_goals < guest_goats then 3 when host_goats ~ guest_goals then 1 else 0 end) as num_points from Matches group by guest_tean dasu group by teamid dasr on t.team_id = r.team_id order by numpoints desc, teamid asc; 01/19/2020 (MySQL # Write your MySQL query statenent below select teamid, team_nane, sun(if(team_id = host_team, case when host_goals > guest_goals then 3 when nost_goals = guest_goals then 1 else 0 end, @)) + sum(if(team_id = guest_tean, case when host_goals < guest_geals then 3 when host_goals = guest_goals then 1 else 0 end, @)) as num_points from Teams as t, Natches as m group by team_id order by num_points desc, team id asc; 1225. Report Contiguous Dates Description Table: Failed | Column Name | Type | faildate | date " Il | a + Primary key for this table is fail_date. Failed table contains the days of failed tasks. Table: Succeeded | Column Nane | Type | success date | date a 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 SOL 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. period_state is ‘failed’ if tasks in this interval failed or ‘succeeded" if tasks in this interval succeeded. Interval of days are retrieved as start_date and end_date. Order result by start_date. The query result format is in the following example: Failed table: + | fail_cate | 2018-12-28 | 2018-12-29 | 2019-01-08, | 2019-01-¢ Succeeded table: ~ | success_date 2018-12-30 2018-12-31 2019-01-01 2019-01-02 2019-01-03 2019-01-06 Result table: = = + | period_state | start_date | enddate | + | succeeded | 2019-01-01 | 2019-01-03 | | failed | 2019-01-04 | 2019-01-25 | | succeeded | 2019-01-06 | 2019-01-06 | + The report ignored the system state in 2018 as we care about the system in the period 2019-01-01 to 2019-12-31. From 2019-01-01 to 2019-01-03 all tasks succeeded and the system state was “succeeded”. From 2019-01-04 to 2019-01-05 all tasks failed and systen state was "failed". From 2019-01-06 to 2019-01-96 all tasks succeeded and systen state was "succeeded"

You might also like