Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Final Document

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 24

1. Consider the following table.

Find out the consecutive numbers that appear


atleast 3 times. Return Number

Query:

SELECT num
FROM (
SELECT id, num,
LAG(num) OVER(ORDER BY id) as prev_num,
LEAD(num) OVER(ORDER BY id) as next_num
FROM numbers
)l
WHERE l.num = l.prev_num
AND l.prev_num = l.next_num
AND l.num = l.next_num;

Output:

—1—
2. Write a solution to find the rank of the scores. The ranking should be
calculated according to the following rules:
 The scores should be ranked from the highest to the lowest.
 If there is a tie between two scores, both should have the same ranking.
 After a tie, the next ranking number should be the next consecutive
integer value. In other words, there should be no holes between ranks.
Return the result table ordered by the score in descending order.

Query:

select score,
dense_rank() over(order by score desc) as rank
from scores
order by score desc;

Output:

—2—
3. Write the employee name who is getting salary more than his manager?

Query:

select distinct e.name as names from employees e,employees m


where e.id = m.manager_id and e.salary > m.salary;

Output:

—3—
4. Write a solution to find managers with at least five direct reports.

Query:

select e.id from employees2 e,employees2 m


where e.id = m.manager_id
group by e.id having count(*)>=5;

Output:

—4—
5. Write a solution 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.

Query:

select * from stadium where people >=100 order by id

Output:

—5—
6. Write a solution to find the people who have the most friends and the most
friends number.

Query:

SELECT req_id, friends


FROM (
SELECT req_id, MAX(count_req_id) AS friends
FROM (
SELECT req_id, COUNT(act_id) AS count_req_id
FROM friends
GROUP BY req_id
)f
GROUP BY req_id
ORDER BY friends DESC
)
WHERE rownum=1;

Output:

—6—
7. Report for every three line segments whether they can form a triangle. The
three segments can form a triangle if the first two sides sum is greater than the
third side.

Query:

SELECT t.*,
CASE
WHEN (x+y >= z AND y+z >= x AND x+z >= y) THEN 'Yes'
ELSE 'No'
END as is_triangle
FROM triangle t;

Output:

—7—
8. A single number is a number that appeared only once in the MyNumbers
table. Find the largest single number. If there is no single number, report null.
The result format is in the following example.

Query:

select max(num) as num from (select num from my_numbers group by num
having count(*)=1);

Output:

—8—
9. Write a solution 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 temporary
tables. Note that you must write a single update statement, do not write any
select statement for this problem.

Query:

update salary
set gender = case when gender = 'm' then 'f' else 'm' end
where gender = 'm' or gender='f';

select * from salary; -- See the results after update

Output:

10. Write a solution to rearrange the Products table so that each row has
(product_id, store, price). If a product is not available in a store, do not include a
row with that product_id and store combination in the result table.
—9—
Query:

select * from(
(
select id,
(case when s1 is not null then 'Store1' end)as Store,
(case when s1 is not null then s1 end)as Price
from products)
union all(
select id,
(case when s2 is not null then 'Store1' end)as Store,
(case when s2 is not null then s2 end)as Price
from products
)union all(
select id,

(case when s3 is not null then 'Store1' end)as Store,


(case when s3 is not null then s3 end)as Price
from products
)
— 10 —
)where store is not null and price is not null
order by id,price;

Output:

11. Write a solution to calculate the bonus of each employee. The bonus of an
employee is 100% of their salary if the ID of the employee is an odd number and
the employee's name does not start with the character 'M'. The bonus of an
employee is 0 otherwise.

Query:

select id,
— 11 —
case
when mod(id,2)!=0 and upper(substr(name,1,1))!='M' then salary
else 0
end as bonus from employees;

Output:

12. Find the IDs of the employees whose salary is strictly less than $30000 and
whose manager left the company. When a manager leaves the company, their
information is deleted from the Employees table, but the reports still have their
manager_id set to the manager that left.

Query:

select id from employees where salary > 30000 and manager_id not in(select
distinct id from employees);
— 12 —
Output:

13. Write a solution to calculate the number of unique subjects each teacher
teaches in the university.

Query:

select id as teacher_id, count(distinct subject_id) as cnt from teacher


group by id;

Output:

14. Employees can belong to multiple departments. When the employee joins
other departments, they need to decide which department is their primary
department. Note that when an employee belongs to only one department,
— 13 —
their primary column is 'N'. Write a solution to report all the employees with
their primary department. For employees who belong to one department,
report their only department.

Query:

(
select id,max(dept_id) as dept_id from employees3 group by id having
count(*)=1
)
union(
select id,dept_id from employees3 where pr='Y'
);

Output:

— 14 —
15. Write a solution to calculate the number of bank accounts for each salary
category. The salary categories are:
a) "Low Salary": All the salaries strictly less than $20000.
b) "Average Salary": All the salaries in the inclusive range [$20000,$50000].
c) "High Salary": All the salaries strictly greater than $50000.
The result table must contain all three categories. If there are no accounts in a
category, return 0.

Query:
select category,accounts_count from( (
SELECT 1 AS SEQ,'Low salary' as category, count(salary) as accounts_count
FROM accounts
WHERE salary < 20000
) union(
SELECT 3 AS SEQ,'High salary' as category, count(salary) as accounts_count
FROM accounts
WHERE salary > 50000
)union (
SELECT 2 AS SEQ,'Average salary' as category, count(salary) as
accounts_count
FROM accounts
WHERE salary between 20000 and 50000
)order by SEQ
);

Output:
— 15 —
16. The confirmation rate of a user is the number of 'confirmed' messages
divided by the total number of requested confirmation messages. The
confirmation rate of a user that did not request any confirmation messages is 0.
Round the confirmation rate to two decimal places.Write a solution to find the
confirmation rate of each user.

— 16 —
Query:

SELECT
s.user_id,
(
SELECT COUNT(*)
FROM signups s2
JOIN confirmations c ON s2.user_id = c.user_id

WHERE c.action = 'confirmed' AND s2.user_id = s.user_id


) / COUNT(*) AS confirmation_rate
FROM
signups s
LEFT JOIN
confirmations c ON s.user_id = c.user_id
GROUP BY
s.user_id;

Output:

— 17 —
17. Write a solution to report the IDs of all the employees with missing
information. The information of an employee is missing if The employee's name
is missing, or The employee's salary is missing. Return the result table ordered
by employee_id in ascending order.

Query:

(select employee_id from salaries where employee_id not in (select


employee_id from employees4))union(
select employee_id from employees4 where employee_id not in (select
employee_id from salaries));

— 18 —
Output:

18. Write a solution to select the product id, year, quantity, and price for the
first year of every product sold.

Query:

SELECT *
FROM (
SELECT s.*, FIRST_VALUE(s.year) OVER(PARTITION BY s.prod_id ORDER BY
s.year) AS first_year

FROM sales s
— 19 —
)
where first_year = year;

Output:

19. Write a solution to find for each user, the join date and the number of
orders they made as a buyer in 2019.

Query:
— 20 —
SELECT O.buyer_id, u.join_date, COUNT(*) AS num_orders
FROM users u
JOIN orders3 o ON u.id = o.BUYER_ID
WHERE EXTRACT(YEAR FROM o.order_date) = 2019
GROUP BY O.buyer_id, u.join_date;

Output:

20. You are the restaurant owner and you want to analyze a possible expansion
(there will be at least one customer every day). Compute the moving average of
how much the customer paid in a seven days window (i.e., current day + 6 days
before). average_amount should be rounded to two decimal places. Return the
result table ordered by visited_on in ascending order.

Query:

SELECT visited_on, amount, average_amount


— 21 —
FROM (SELECT * FROM (
SELECT
visited_on,
SUM(amount) OVER (ORDER BY visited_on) as amount,
ROUND(AVG(amount) OVER (ORDER BY visited_on), 2) AS average_amount,
ROW_NUMBER() OVER(ORDER BY visited_on) AS day

FROM
customers
)t
where t.day>7
);

Output:

21. Write a solution to find the name of the user who has rated the greatest
number of movies. In case of a tie, return the lexicographic smaller user name.
Find the movie name with the highest average rating in February 2020. In case
of a tie, return the lexicographical smaller movie name.
— 22 —
Query:

(select name as results from


(select b.name,max(a.rating) as rating from ratings a,users2 b where a.user_id
= b.id group by b.name
order by max(a.rating) desc)
where rownum = 1
)union(
select title from
(select b.title, avg(a.rating) as average_rating from ratings a, movies b where
a.mov_id = b.id
group by b.title order by avg(a.rating) desc)
where rownum = 1
);

Output:

— 23 —
— 24 —

You might also like