├── 1050. Actors and Directors Who Cooperated At Least Three Times.sql ├── 1068. Product Sales Analysis I.sql ├── 1069. Product Sales Analysis II.sql ├── 1075. Project Employees I.sql ├── 1076. Project Employees II.sql ├── 1082. Sales Analysis I.sql ├── 1083. Sales Analysis II.sql ├── 1084. Sales Analysis III.sql ├── 1113. Reported Posts.sql ├── 1141. User Activity for the Past 30 Days I.sql ├── 1142. User Activity for the Past 30 Days II.sql ├── 1148. Article Views I.sql ├── 1173. Immediate Food Delivery I.sql ├── 1179. Reformat Department Table.sql ├── 1211. Queries Quality and Percentage.sql ├── 1241. Number of Comments per Post.sql ├── 1251. Average Selling Price. sql ├── 1270. All People Report to the Given Manager.sql ├── 1294. Weather Type in Each Country.sql ├── 1303. Find the Team Size.sql ├── 1308. Running Total for Different Genders.sql ├── 1327. List the Products Ordered in a Period.sql ├── 1350. Students With Invalid Departments.sql ├── 1378. Replace Employee ID With The Unique Identifier.sql ├── 1393. Capital Gain Loss.sql ├── 1398. Customers Who Bought Products A and B but Not C.sql ├── 1407. Top Travellers.sql ├── 1421. NPV Queries.sql ├── 1445. Apples & Oranges ├── 1468. Calculate Salaries.sql ├── 1484. Group Sold Products By The Date.sql ├── 1495. Friendly Movies Streamed Last Month.sql ├── 1527. Patients With a Condition.sql ├── 1565. Unique Orders and Customers Per Month.sql ├── 1571. Warehouse Manager.sql ├── 1581. Customer Who Visited but Did Not Make Any Transactions.sql ├── 1587. Bank Account Summary II.sql ├── 1607. Sellers With No Sales.sql ├── 1623. All Valid Triplets That Can Represent a Country.sql ├── 1633. Percentage of Users Attended a Contest.sql ├── 1661. Average Time Of Process Per Machine.sql ├── 1677. Product's Worth Over Invoices.sql ├── 1683. Invalid Tweets.sql ├── 1693. Daily Leads and Partners.sql ├── 1709. Biggest Window Between Visits.sql ├── 1729. Find Followers Count.sql ├── 1731. The Number of Employees Which Report to Each Employee.sql ├── 1741. Find Total Time Spent by Each Employee1741. Find Total Time Spent by Each Employee.sql ├── 1757. Recyclable and Low Fat Products.sql ├── 176. Second Highest Salary .sql ├── 176. Second Highest Salary.sql ├── 177. Nth Highest Salary.sql ├── 1777. Product's Price for Each Store.sql ├── 178. Rank Scores.sql ├── 1789. Primary Department for Each Employee.sql ├── 1795. Rearrange Products Table.sql ├── 180. Consecutive Numbers.sql ├── 181. Employees Earning More Than Their Managers.sql ├── 182. Duplicate Emails.sql ├── 1821. Find Customers With Positive Revenue this Year.sql ├── 183. Customers Who Never Order.sql ├── 185. Department Top Three Salaries.sql ├── 1853. Convert Date Format.sql ├── 1873. Calculate Special Bonus .sql ├── 1890. The Latest Login in 2020.sql ├── 196. Delete Duplicate Emails.sql ├── 511. Game Play Analysis I.sql ├── 512. Game Play Analysis II.sql ├── 534. Game Play Analysis III ├── 577. Employee Bonus.sql ├── 584. Find Customer Referee.sql ├── 586. Customer Placing the Largest Number of Orders.sql ├── 595. Big Countries.sql ├── 596. Classes More Than 5 Students.sql ├── 607. Sales Person.sql ├── 610. Triangle Judgement.sql ├── 613. Shortest Distance in a Line.sql ├── 619. Biggest Single Number.sql ├── 620. Not Boring Movies.sql └── README.md /1050. Actors and Directors Who Cooperated At Least Three Times.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select actor_id, director_id 3 | from ActorDirector 4 | group by actor_id,director_id 5 | having count(timestamp)>=3 6 | -------------------------------------------------------------------------------- /1068. Product Sales Analysis I.sql: -------------------------------------------------------------------------------- 1 | select product_name, year, price 2 | from product 3 | join sales on sales.product_id=product.product_id 4 | group by product_name, year,price 5 | order by product_name, year,price 6 | -------------------------------------------------------------------------------- /1069. Product Sales Analysis II.sql: -------------------------------------------------------------------------------- 1 | select product_id, sum(quantity) as total_quantity 2 | from sales 3 | group by product_id 4 | -------------------------------------------------------------------------------- /1075. Project Employees I.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select project_id,round(avg(experience_years),2) as average_years 3 | from project 4 | join employee on project.employee_id=employee.employee_id 5 | group by project_id 6 | -------------------------------------------------------------------------------- /1076. Project Employees II.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select project_id 3 | from project 4 | group by project_id 5 | having count(*)= (select count(employee_id) from project group by project_id order by count(employee_id) desc limit 1) 6 | -------------------------------------------------------------------------------- /1082. Sales Analysis I.sql: -------------------------------------------------------------------------------- 1 | # subquries 2 | select seller_id 3 | from sales 4 | group by seller_id 5 | having sum(price) = (select max(total) from (select seller_id, sum(price) as total from sales group by seller_id) t1) 6 | -------------------------------------------------------------------------------- /1083. Sales Analysis II.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select distinct buyer_id 3 | from sales join product using(product_id) 4 | where product_name = 'S8' 5 | and buyer_id not in (select distinct buyer_id 6 | from sales join product using(product_id) 7 | where product_name = 'iPhone' ) 8 | 9 | 10 | SELECT 11 | DISTINCT buyer_id 12 | FROM 13 | Sales 14 | WHERE 15 | buyer_id IN ( SELECT 16 | s.buyer_id 17 | FROM 18 | Sales s 19 | INNER JOIN 20 | Product p 21 | ON s.product_id = p.product_id 22 | WHERE 23 | product_name = 'S8') 24 | AND buyer_id NOT IN (SELECT 25 | s.buyer_id 26 | FROM 27 | Sales s 28 | INNER JOIN 29 | Product p 30 | ON s.product_id = p.product_id 31 | WHERE 32 | product_name = 'iPhone'); 33 | 34 | 35 | SELECT s.buyer_id 36 | FROM Sales AS s INNER JOIN Product AS p 37 | ON s.product_id = p.product_id 38 | GROUP BY s.buyer_id 39 | HAVING SUM(CASE WHEN p.product_name = 'S8' THEN 1 ELSE 0 END) > 0 40 | AND SUM(CASE WHEN p.product_name = 'iPhone' THEN 1 ELSE 0 END) = 0; 41 | -------------------------------------------------------------------------------- /1084. Sales Analysis III.sql: -------------------------------------------------------------------------------- 1 | select 2 | product_id, product_name 3 | from product 4 | where product_id not in 5 | (select product_id 6 | from sales 7 | where sale_date <'2019-01-01'or sale_date>'2019-03-31') 8 | -------------------------------------------------------------------------------- /1113. Reported Posts.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select extra as report_reason, count(distinct post_id) as report_count 3 | from actions 4 | where action='report' and extra is not null 5 | and action_date between '2019-07-04' and '2019-07-06' 6 | group by report_reason 7 | -------------------------------------------------------------------------------- /1141. User Activity for the Past 30 Days I.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select activity_date as day,count(distinct user_id) as active_users 3 | from activity 4 | where activity_date between '2019-06-28' and '2019-07-27' 5 | group by activity_date; 6 | 7 | 8 | select activity_date as day, count(distinct user_id) as active_users 9 | from Activity 10 | where datediff('2019-07-27', activity_date) <30 11 | group by activity_date; 12 | 13 | 14 | -------------------------------------------------------------------------------- /1142. User Activity for the Past 30 Days II.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select round(ifnull(count(distinct session_id)/count(distinct user_id),0),2) as average_sessions_per_user 3 | from activity 4 | where activity_date between '2019-06-28' and '2019-07-27' 5 | 6 | 7 | # date_sub() 8 | select round(ifnull(count(distinct session_id)/count(distinct user_id),0),2) as average_sessions_per_user 9 | from activity 10 | where activity_date between date_sub('2019-07-27',interval 29 day) and '2019-07-27' 11 | -------------------------------------------------------------------------------- /1148. Article Views I.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select author_id as id 3 | from views 4 | where author_id=viewer_id 5 | group by id 6 | order by id 7 | -------------------------------------------------------------------------------- /1173. Immediate Food Delivery I.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select round(100* 3 | (select count(*) from delivery where order_Date = customer_pref_delivery_date) 4 | / 5 | (select count(*) from delivery) 6 | ,2) as immediate_percentage 7 | -------------------------------------------------------------------------------- /1179. Reformat Department Table.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select id, 3 | sum(case when month='Jan' then revenue end) as Jan_revenue, 4 | sum(case when month='Feb' then revenue end) as Feb_revenue, 5 | sum(case when month='Mar' then revenue end) as Mar_revenue, 6 | sum(case when month='Apr' then revenue end) as Apr_revenue, 7 | sum(case when month='May' then revenue end) as May_revenue, 8 | sum(case when month='Jun' then revenue end) as Jun_revenue, 9 | sum(case when month='Jul' then revenue end) as Jul_revenue, 10 | sum(case when month='Aug' then revenue end) as Aug_revenue, 11 | sum(case when month='Sep' then revenue end) as Sep_revenue, 12 | sum(case when month='Oct' then revenue end) as Oct_revenue, 13 | sum(case when month='Nov' then revenue end) as Nov_revenue, 14 | sum(case when month='Dec' then revenue end) as Dec_revenue 15 | from department 16 | group by id 17 | -------------------------------------------------------------------------------- /1211. Queries Quality and Percentage.sql: -------------------------------------------------------------------------------- 1 | select query_name, round(avg(rating/position),2) quality, 2 | round(count(case when rating<3 then 1 end)/count(query_name)*100,2) poor_query_percentage 3 | from queries 4 | group by query_name; 5 | -------------------------------------------------------------------------------- /1241. Number of Comments per Post.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select parent as post_id,ifnull(count(distinct sub_id),0) as number_of_comments 3 | from (select sub_id as parent from submissions where parent_id is null) p 4 | left join (select sub_id,parent_id from submissions where parent_id is not null) c 5 | on p.parent=c.parent_id 6 | group by parent 7 | 8 | 9 | -------------------------------------------------------------------------------- /1251. Average Selling Price. sql: -------------------------------------------------------------------------------- 1 | select product_id, round(sum(price*units)/sum(units),2) as average_price 2 | from unitssold 3 | join prices 4 | using (product_id) 5 | where purchase_date >= start_date and purchase_date <= end_date 6 | group by product_id 7 | -------------------------------------------------------------------------------- /1270. All People Report to the Given Manager.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select employee_id 3 | from employees 4 | where manager_id = 1 and employee_id <>1 5 | union 6 | select employee_id 7 | from employees 8 | where manager_id in (select employee_id 9 | from employees 10 | where manager_id = 1 and employee_id <>1) 11 | union 12 | select employee_id 13 | from employees 14 | where manager_id in (select employee_id 15 | from employees 16 | where manager_id in (select employee_id 17 | from employees 18 | where manager_id = 1 and employee_id <>1)); 19 | 20 | 21 | 22 | # 23 | SELECT e1.employee_id 24 | FROM Employees e1, 25 | Employees e2, 26 | Employees e3 27 | WHERE e1.manager_id = e2.employee_id 28 | AND e2.manager_id = e3.employee_id 29 | AND e3.manager_id = 1 30 | AND e1.employee_id != 1; 31 | 32 | 33 | # 34 | with recursive cte as 35 | ( 36 | select employee_id from employees where manager_id=1 and employee_id!=1 37 | union all 38 | select a.employee_id from employees a join cte b on (b.employee_id=a.manager_id) 39 | ) 40 | select employee_id from cte 41 | -------------------------------------------------------------------------------- /1294. Weather Type in Each Country.sql: -------------------------------------------------------------------------------- 1 | select country_name, 2 | case 3 | when avg(weather_state)<=15 then 'Cold' 4 | when avg(weather_state)>=25 then 'Hot' 5 | else 'Warm' end as weather_type 6 | from weather 7 | join countries on weather.country_id=countries.country_id 8 | where day between '2019-11-01' and '2019-11-30' 9 | group by country_name 10 | -------------------------------------------------------------------------------- /1303. Find the Team Size.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select employee_id, team_size 3 | from employee 4 | join (select team_id, count(*) as team_size from employee group by team_id) team 5 | on employee.team_id=team.team_id 6 | 7 | 8 | # Window Functions 9 | select employee_id, count(employee_id) over(partition by team_id) as team_size 10 | from Employee 11 | -------------------------------------------------------------------------------- /1308. Running Total for Different Genders.sql: -------------------------------------------------------------------------------- 1 | select gender,day,sum(score_points) over (partition by gender order by gender, day) as total 2 | from scores 3 | -------------------------------------------------------------------------------- /1327. List the Products Ordered in a Period.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select product_name as PRODUCT_NAME, sum(unit) as UNIT 3 | from products 4 | join orders on products.product_id=orders.product_id 5 | where order_date > '2020-01-31' and order_date<'2020-03-01' 6 | group by product_name 7 | having sum(unit) >99 8 | 9 | 10 | 11 | # Write your MySQL query statement below 12 | select product_name, sum(unit) as unit 13 | from products 14 | join orders 15 | using (product_id) 16 | where month(order_date)=2 17 | group by product_id 18 | having sum(unit)>=100 19 | -------------------------------------------------------------------------------- /1350. Students With Invalid Departments.sql: -------------------------------------------------------------------------------- 1 | # Exists: 2 | # Write your MySQL query statement below 3 | SELECT id, name 4 | FROM Students s 5 | WHERE NOT EXISTS ( 6 | SELECT id 7 | FROM Departments 8 | WHERE id = s.department_id 9 | ); 10 | 11 | 12 | # Not In 13 | SELECT id, name FROM Students 14 | WHERE department_id not in (SELECT id from Departments); 15 | 16 | 17 | # Left/Right Join 18 | select s.id as id, s.name as name 19 | from students s 20 | left join departments d 21 | on s.department_id = d.id 22 | where d.name is null 23 | group by id, name 24 | -------------------------------------------------------------------------------- /1378. Replace Employee ID With The Unique Identifier.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select unique_id, name 3 | from employeeUNI 4 | right join Employees on EmployeeUNI.id=employees.id 5 | 6 | # Write your MySQL query statement below 7 | select unique_id,name 8 | from employeeuni 9 | right join employees 10 | using (id) 11 | 12 | -------------------------------------------------------------------------------- /1393. Capital Gain Loss.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select stock_name, sum(if(operation='sell', price,-price)) as capital_gain_loss 3 | from stocks 4 | group by stock_name 5 | -------------------------------------------------------------------------------- /1398. Customers Who Bought Products A and B but Not C.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | 3 | select customer_id,customer_name 4 | from customers 5 | where customer_id in (select customer_id from orders where product_name = 'A') 6 | and customer_id in (select customer_id from orders where product_name = 'B') 7 | and customer_id not in (select customer_id from orders where product_name = 'C') 8 | group by 1,2 9 | 10 | 11 | -------------------------------------------------------------------------------- /1407. Top Travellers.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select name, ifnull(sum(distance),0) as travelled_distance 3 | from users 4 | left join rides on users.id=rides.user_id 5 | group by name 6 | order by travelled_distance desc, name 7 | -------------------------------------------------------------------------------- /1421. NPV Queries.sql: -------------------------------------------------------------------------------- 1 | select queries.id, queries.year, ifnull(npv, 0) as npv 2 | from queries 3 | left join NPV 4 | on queries.id = NPV.id and Queries.year = NPV.year; 5 | -------------------------------------------------------------------------------- /1445. Apples & Oranges: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select sale_date, sum(case when fruit='apples' then sold_num else -sold_num end) as diff 3 | from sales 4 | group by sale_date 5 | order by sale_date 6 | 7 | # sum(if) 8 | SELECT 9 | sale_date, 10 | SUM(IF(fruit = 'apples', sold_num, -sold_num)) AS diff 11 | FROM Sales 12 | GROUP BY sale_date 13 | 14 | 15 | # Join 16 | select distinct a.sale_date, (a.sold_num - b.sold_num) as diff 17 | from 18 | ( 19 | select sale_date, fruit, sold_num 20 | from Sales 21 | where fruit = 'apples' 22 | ) a 23 | join 24 | ( 25 | select sale_date, fruit, sold_num 26 | from Sales 27 | where fruit = 'oranges' 28 | ) b 29 | on a.sale_date = b.sale_date 30 | -------------------------------------------------------------------------------- /1468. Calculate Salaries.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | 3 | select company_id, employee_id,employee_name, 4 | round(case when max(salary) over (partition by company_id) between 1000 and 10000 then (1-0.24)*salary 5 | when max(salary) over (partition by company_id) > 10000 then (1-0.49)*salary else salary end,0) as salary 6 | from salaries 7 | -------------------------------------------------------------------------------- /1484. Group Sold Products By The Date.sql: -------------------------------------------------------------------------------- 1 | /* Group_Concat ->returns a string with concatenated non-NULL value from a group. 2 | Returns NULL when there are no non-NULL values 3 | 4 | GROUP_CONCAT(DISTINCT cate_id ORDER BY cate_id ASC SEPARATOR ' ') 5 | */ 6 | 7 | 8 | select sell_date, count(distinct product) as num_sold, group_concat(distinct product) as products 9 | from activities 10 | group by sell_date 11 | 12 | 13 | /* String_AGG-> SQL Server 14 | STRING_AGG ( expression, separator ) [ ] 15 | 16 | ::= 17 | WITHIN GROUP ( ORDER BY [ ASC | DESC ] ) 18 | */ 19 | 20 | select t.sell_date, count(*) as num_sold, string_agg(product,',') as products 21 | from (select distinct * from activities) as t 22 | group by t.sell_date 23 | order by t.sell_date 24 | -------------------------------------------------------------------------------- /1495. Friendly Movies Streamed Last Month.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select distinct title 3 | from content 4 | join TVProgram USING (content_id) 5 | where program_date between '2020-06-01' and '2020-06-30' 6 | and kids_content="Y" and content_type='Movies' 7 | -------------------------------------------------------------------------------- /1527. Patients With a Condition.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select * 3 | from patients 4 | where conditions like '%DIAB1%' 5 | -------------------------------------------------------------------------------- /1565. Unique Orders and Customers Per Month.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select DATE_FORMAT(order_date, '%Y-%m') AS month, count(order_id) as order_count, count(distinct(customer_id)) as customer_count 3 | from orders 4 | where invoice>20 5 | group by month 6 | 7 | 8 | 9 | Using concat(year(order_date), '-',mont(order_date)) as month but formatting is different than the answer. Still a good solution 10 | -------------------------------------------------------------------------------- /1571. Warehouse Manager.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select w.name as WAREHOUSE_NAME, sum(p2.volume * w.units) as VOLUME 3 | from warehouse w 4 | join (select p.product_id as product_id, p.product_name as product_name, (p.width * p.length * p.height) as volume 5 | from products p 6 | group by product_id, product_name) p2 on w.product_id = p2.product_id 7 | group by warehouse_name 8 | 9 | 10 | 11 | # Write your MySQL query statement below 12 | with ware_prod as 13 | (select w.name as name, p.product_id, w.units as units, width*length*height as pro_volume 14 | from products p 15 | join 16 | warehouse w on p.product_id=w.product_id) 17 | select name as warehouse_name,sum(pro_volume*units) as volume 18 | from ware_prod 19 | group by name 20 | 21 | 22 | -------------------------------------------------------------------------------- /1581. Customer Who Visited but Did Not Make Any Transactions.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select customer_id, count(*) as count_no_trans 3 | from visits 4 | where visit_id not in (select distinct visit_id from transactions) 5 | group by customer_id; 6 | 7 | # Left Join 8 | SELECT 9 | customer_id, 10 | COUNT(Visits.visit_id) AS count_no_trans 11 | FROM 12 | visits 13 | LEFT JOIN Transactions 14 | ON Visits.visit_id = Transactions.visit_id 15 | WHERE 16 | Transactions.visit_id IS NULL 17 | GROUP BY customer_id; 18 | 19 | # CTE 20 | with t as 21 | (select customer_id, count(transaction_id) cnt 22 | from visits 23 | left join transactions using(visit_id) 24 | group by 1, visit_id 25 | having count(transaction_id)=0) 26 | 27 | select customer_id, count(cnt) count_no_trans 28 | from t 29 | group by 1 30 | 31 | # Exists 32 | select customer_id, count(*) count_no_trans 33 | from 34 | Visits 35 | where NOT EXISTS ( 36 | select * from Transactions 37 | where Visits.visit_id=Transactions.visit_id 38 | ) 39 | group by customer_id; 40 | -------------------------------------------------------------------------------- /1587. Bank Account Summary II.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select name, sum(amount) as balance 3 | from users u 4 | join transactions t on u.account=t.account 5 | group by name 6 | having balance > 10000 7 | -------------------------------------------------------------------------------- /1607. Sellers With No Sales.sql: -------------------------------------------------------------------------------- 1 | select seller_name 2 | from seller 3 | where seller_name not in ( 4 | select seller_name 5 | from seller 6 | join orders on seller.seller_id=orders.seller_id 7 | where year(sale_date)=2020 8 | group by seller_name) 9 | group by seller_name 10 | order by seller_name 11 | -------------------------------------------------------------------------------- /1623. All Valid Triplets That Can Represent a Country.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select a.student_name as member_A,b.student_name as member_B,c.student_name as member_C 3 | from schoola a 4 | cross join schoolb b 5 | cross join schoolc c 6 | where a.student_name <> b.student_name and b.student_name <> c.student_name and a.student_name <> c.student_name 7 | and a.student_id <> b.student_id and b.student_id <> c.student_id and a.student_id <> c.student_id 8 | 9 | -------------------------------------------------------------------------------- /1633. Percentage of Users Attended a Contest.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select contest_id,round(count(user_id)/(select count(user_id) from users)*100,2) as percentage 3 | from register 4 | group by contest_id 5 | order by percentage desc, contest_id 6 | -------------------------------------------------------------------------------- /1661. Average Time Of Process Per Machine.sql: -------------------------------------------------------------------------------- 1 | with temp as ( 2 | select machine_id, 3 | process_id, 4 | sum(case when activity_type = 'end' then timestamp end)-sum(case when activity_type = 'start' then timestamp end) durations 5 | from Activity 6 | group by machine_id, process_id) 7 | select machine_id, round(avg(durations),3) as processing_time 8 | from temp 9 | group by 1 10 | -------------------------------------------------------------------------------- /1677. Product's Worth Over Invoices.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select name as name, sum(rest) as rest, sum(paid) as paid, sum(canceled) as canceled, sum(refunded) as refunded 3 | from invoice 4 | Right join product 5 | using (product_id) 6 | group by name 7 | order by name 8 | 9 | # why not using Inner Join even through get the result? because it is about "all products" 10 | -------------------------------------------------------------------------------- /1683. Invalid Tweets.sql: -------------------------------------------------------------------------------- 1 | SELECT tweet_id 2 | FROM Tweets 3 | WHERE LENGTH(content) > 15; 4 | -------------------------------------------------------------------------------- /1693. Daily Leads and Partners.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select date_id, make_name, count(distinct lead_id) as unique_leads, count(distinct partner_id) as unique_partners 3 | from dailysales 4 | group by date_id,make_name 5 | -------------------------------------------------------------------------------- /1709. Biggest Window Between Visits.sql: -------------------------------------------------------------------------------- 1 | select user_id, max(abs(datediff(visit_date1,visit_date2))) as biggest_window 2 | from(select user_id, 3 | visit_date as visit_date1, 4 | ifnull(lead(visit_date) over (partition by user_id order by visit_date), '2021-1-1') as visit_date2 5 | from uservisits) tb 6 | group by user_id 7 | -------------------------------------------------------------------------------- /1729. Find Followers Count.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select distinct user_id, count(follower_id) as followers_count 3 | from followers 4 | order by user_id 5 | -------------------------------------------------------------------------------- /1731. The Number of Employees Which Report to Each Employee.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select m.employee_id as employee_id,m.name as name,count(e.employee_id) as reports_count,round(avg(e.age),0) as average_age 3 | from employees m 4 | join (select * from employees where reports_to is not null) e 5 | on m.employee_id=e.reports_to 6 | group by 1,2 7 | order by 1 8 | -------------------------------------------------------------------------------- /1741. Find Total Time Spent by Each Employee1741. Find Total Time Spent by Each Employee.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select event_day as day, emp_id, sum(duration) as total_time 3 | from (select event_day, emp_id, out_time-in_time as duration from employees) as emp_timestamps 4 | group by event_day, emp_id; 5 | 6 | 7 | SELECT EVENT_DAY AS DAY, EMP_ID, (SUM(OUT_TIME)-SUM(IN_TIME)) AS TOTAL_TIME 8 | FROM EMPLOYEES GROUP BY DAY, EMP_ID; 9 | -------------------------------------------------------------------------------- /1757. Recyclable and Low Fat Products.sql: -------------------------------------------------------------------------------- 1 | select product_id 2 | from products 3 | where low_fats = 'Y' and recyclable = 'Y' 4 | -------------------------------------------------------------------------------- /176. Second Highest Salary .sql: -------------------------------------------------------------------------------- 1 | # Write your MSSQL query statement below 2 | select max(salary) as SecondHighestSalary from employee 3 | where salary not in (select max(salary) from employee) 4 | -------------------------------------------------------------------------------- /176. Second Highest Salary.sql: -------------------------------------------------------------------------------- 1 | # limit offset 2 | SELECT 3 | (SELECT DISTINCT 4 | Salary 5 | FROM 6 | Employee 7 | ORDER BY Salary DESC 8 | LIMIT 1 OFFSET 1) AS SecondHighestSalary 9 | 10 | 11 | 12 | 13 | 14 | #dense_rank() 15 | 16 | with CTE as( 17 | select salary, dense_rank() over (order by Salary DESC) as grader from Employee) 18 | 19 | select max(salary) as SecondHighestSalary from CTE 20 | where grader=2 21 | 22 | -------------------------------------------------------------------------------- /177. Nth Highest Salary.sql: -------------------------------------------------------------------------------- 1 | /* 2 | * Order By Clause 3 | * ORDER BY order_by_expression 4 | [ COLLATE collation_name ] 5 | [ ASC | DESC ] 6 | [ ,...n ] 7 | [ ] 8 | 9 | ::= 10 | { 11 | OFFSET { integer_constant | offset_row_count_expression } { ROW | ROWS } 12 | [ 13 | FETCH { FIRST | NEXT } {integer_constant | fetch_row_count_expression } { ROW | ROWS } ONLY 14 | ] 15 | } 16 | */ 17 | 18 | Create FUNCTION getNthHighestSalary(@N INT) returns INT as 19 | BEGIN 20 | Return( 21 | Select Salary 22 | From Employee 23 | Gourp By Salary 24 | Order By Salary DESC 25 | Offset @N-1 rows 26 | Fetch First 1 Rows Only 27 | ); 28 | End 29 | -------------------------------------------------------------------------------- /1777. Product's Price for Each Store.sql: -------------------------------------------------------------------------------- 1 | select product_id, 2 | sum(case when store = 'store1' then price else null end) store1, 3 | sum(case when store = 'store2' then price else null end) store2, 4 | sum(case when store = 'store3' then price else null end) store3 5 | from products 6 | group by product_id 7 | 8 | -- (My SQL) 9 | -------------------------------------------------------------------------------- /178. Rank Scores.sql: -------------------------------------------------------------------------------- 1 | /* 2 | * Over Clause 3 | * defines a window or user-specified set of rows within a query result set. 4 | * usable in Ranking Functions, Aggregate Functions. Analytics Functions, and Next Value For Functions 5 | * OVER ( [ PARTITION BY value_expression ] [ order_by_clause ] ) 6 | * Ranking -> Rank 7 | * Returns the rank of each row within the partition of a result set. 8 | * is a temporary value 9 | * RANK ( ) OVER ( [ partition_by_clause ] order_by_clause ) 10 | * ranking after a tie will be skipped with RANK() function 11 | * Ranking -> Dense_Rank 12 | * This function returns the rank of each row within a result set partition, with no gaps in the ranking values. 13 | * DENSE_RANK ( ) OVER ( [ ] < order_by_clause > ) 14 | * ranking after a tie will not be skipped with RANK() function 15 | * Ranking -> NTILE 16 | * returns the number of the group to which the row belongs. 17 | * starting at one 18 | * NTILE (integer_expression) OVER ( [ ] < order_by_clause > ) 19 | * Ranking -> Row_Number 20 | * returns the sequential number of a row within a partition of a result set 21 | * is temporary value 22 | * ROW_NUMBER ( ) OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_by_clause ) 23 | */ 24 | 25 | /* The ranking score is asking for rank with no skips. Therefore, dense_rank will be the best option for this case */ 26 | select score, dense_rank() over (order by score desc) as rank 27 | from scores 28 | order by rank 29 | -------------------------------------------------------------------------------- /1789. Primary Department for Each Employee.sql: -------------------------------------------------------------------------------- 1 | # The following solution provided by @BilalSubhani: https://github.com/BilalSubhani 2 | # Thank you! 3 | 4 | WITH EmployeeCounts AS ( 5 | SELECT 6 | employee_id, 7 | COUNT(*) AS count, 8 | MAX(primary_flag) AS primary_flag 9 | FROM 10 | Employee 11 | GROUP BY 12 | employee_id 13 | ) 14 | SELECT 15 | e.employee_id, 16 | COALESCE( 17 | MAX(CASE WHEN e.primary_flag = 'Y' THEN e.department_id ELSE NULL END), 18 | MIN(CASE WHEN e.primary_flag = 'N' THEN e.department_id ELSE NULL END) 19 | ) AS department_id 20 | FROM 21 | Employee e 22 | JOIN 23 | EmployeeCounts ec ON e.employee_id = ec.employee_id 24 | GROUP BY 25 | e.employee_id 26 | HAVING 27 | COUNT(CASE WHEN e.primary_flag = 'Y' THEN e.department_id ELSE NULL END) = 1 28 | OR COUNT(CASE WHEN e.primary_flag = 'N' THEN e.department_id ELSE NULL END) = 1 29 | OR 'Y' IN (SELECT primary_flag FROM Employee WHERE employee_id = e.employee_id); 30 | 31 | 32 | 33 | 34 | # old solution, won't work after the test changed 35 | select employee_id, department_id 36 | from employee 37 | group by employee_id 38 | having count(employee_id)=1 39 | union 40 | select employee_id, department_id 41 | from employee 42 | where primary_flag = 'Y' 43 | -------------------------------------------------------------------------------- /1795. Rearrange Products Table.sql: -------------------------------------------------------------------------------- 1 | -- mySQL solution 2 | SELECT product_id, 'store1' store, store1 price 3 | FROM Products 4 | where store1 is not null 5 | union 6 | SELECT product_id, 'store2' store, store2 price 7 | FROM Products 8 | where store2 is not null 9 | union 10 | SELECT product_id, 'store3' store, store3 price 11 | FROM Products 12 | where store3 is not null; 13 | 14 | /* since mySQL doesn't have unpivot operator, needs to be remodifying the table before union */ 15 | 16 | --MSSQL solution 17 | 18 | SELECT product_id,store,price 19 | FROM Products 20 | UNPIVOT 21 | ( 22 | price 23 | FOR store in (store1,store2,store3) 24 | ) AS StorePivot; 25 | -------------------------------------------------------------------------------- /180. Consecutive Numbers.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select l1.num as ConsecutiveNums 3 | from logs l1 4 | join logs l2 on l1.id+1=l2.id 5 | join logs l3 on l2.id+1=l3.id 6 | where l1.num=l2.num and l2.num=l3.num and l3.num=l1.num 7 | group by ConsecutiveNums 8 | -------------------------------------------------------------------------------- /181. Employees Earning More Than Their Managers.sql: -------------------------------------------------------------------------------- 1 | select employee.name as Employee 2 | from employee as employee 3 | inner join employee as manager on employee.managerID=manager.id 4 | where employee.salary>manager.salary 5 | -------------------------------------------------------------------------------- /182. Duplicate Emails.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select email 3 | from person 4 | group by email 5 | having count(email)>1 6 | -------------------------------------------------------------------------------- /1821. Find Customers With Positive Revenue this Year.sql: -------------------------------------------------------------------------------- 1 | select customer_id 2 | from customers 3 | where year = 2021 4 | group by customer_id 5 | having sum(revenue)>0 6 | -------------------------------------------------------------------------------- /183. Customers Who Never Order.sql: -------------------------------------------------------------------------------- 1 | select customers.name as Customers 2 | from customers 3 | left join orders on customers.id=orders.customerId 4 | Where orders.id is null 5 | -------------------------------------------------------------------------------- /185. Department Top Three Salaries.sql: -------------------------------------------------------------------------------- 1 | select department, employee, salary from 2 | (select d.name as Department, e.name as Employee, e.salary as Salary, DENSE_RANK() over 3 | (Partition by d.name order by e.salary desc) as dpt_sal_ranking 4 | from employee e 5 | inner join department as d on e.departmentid = d.id) dpt_sal 6 | where dpt_sal_ranking <4 7 | -------------------------------------------------------------------------------- /1853. Convert Date Format.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select date_format(day,"%W, %M %e, %Y") as day 3 | from Days 4 | 5 | 6 | 7 | #https://www.w3schools.com/mysql/func_mysql_date_format.asp 8 | -------------------------------------------------------------------------------- /1873. Calculate Special Bonus .sql: -------------------------------------------------------------------------------- 1 | select employee_id, (case when name not like 'M%' and (employee_id%2)>0 then salary else 0 end) as bonus 2 | from employees 3 | -------------------------------------------------------------------------------- /1890. The Latest Login in 2020.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select user_id,max(time_stamp) as last_stamp 3 | from logins 4 | where year(time_stamp)=2020 5 | group by user_id 6 | -------------------------------------------------------------------------------- /196. Delete Duplicate Emails.sql: -------------------------------------------------------------------------------- 1 | delete from person where id not in 2 | (select min(id) from (select * from person) person group by email) 3 | -------------------------------------------------------------------------------- /511. Game Play Analysis I.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select player_id, min(event_date) as first_login 3 | from activity 4 | group by player_id 5 | -------------------------------------------------------------------------------- /512. Game Play Analysis II.sql: -------------------------------------------------------------------------------- 1 | select player_id, device_id 2 | from activity 3 | where (player_id, event_date) in ( 4 | select player_id, min(event_date) 5 | from activity 6 | group by player_id 7 | ) 8 | -------------------------------------------------------------------------------- /534. Game Play Analysis III: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select player_id,event_date, sum(games_played) over (partition by player_id order by event_date) as games_played_so_far 3 | from activity 4 | -------------------------------------------------------------------------------- /577. Employee Bonus.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select name, bonus 3 | from employee 4 | left join bonus on employee.empid=bonus.empid 5 | where bonus is null or bonus<1000 6 | -------------------------------------------------------------------------------- /584. Find Customer Referee.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT name 3 | FROM customer 4 | WHERE referee_id <> 2 OR referee_id IS NULL 5 | -------------------------------------------------------------------------------- /586. Customer Placing the Largest Number of Orders.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select customer_number 3 | from orders 4 | group by customer_number 5 | order by count(*) desc 6 | limit 1 7 | -------------------------------------------------------------------------------- /595. Big Countries.sql: -------------------------------------------------------------------------------- 1 | select name, population, area 2 | from world 3 | where area >= 3000000 or population >= 25000000 4 | -------------------------------------------------------------------------------- /596. Classes More Than 5 Students.sql: -------------------------------------------------------------------------------- 1 | select class 2 | from courses 3 | group by class 4 | having count(distinct student)>4 5 | -------------------------------------------------------------------------------- /607. Sales Person.sql: -------------------------------------------------------------------------------- 1 | # Others' answer 2 | select salesperson.name 3 | from orders o join company c on (o.com_id = c.com_id and c.name = 'RED') 4 | right join salesperson on salesperson.sales_id = o.sales_id 5 | where o.sales_id is null; 6 | 7 | # Write your MySQL query statement below 8 | select name 9 | from salesperson 10 | where name not in 11 | (select sp.name 12 | from salesperson sp 13 | join orders o on sp.sales_id=o.sales_id 14 | join company c on o.com_id=c.com_id 15 | where c.name='Red') 16 | -------------------------------------------------------------------------------- /610. Triangle Judgement.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select x,y,z, 3 | (case when x+y>z and y+z>x and z+x>y then 'Yes' else 'No' end) as triangle 4 | from triangle 5 | -------------------------------------------------------------------------------- /613. Shortest Distance in a Line.sql: -------------------------------------------------------------------------------- 1 | # Cross Join 2 | # Write your MySQL query statement below 3 | select min(abs(p1.x-p2.x)) as shortest 4 | from point p1 5 | cross join point p2 6 | where p1.x<>p2.x; 7 | 8 | 9 | # Inner Join 10 | SELECT 11 | MIN(ABS(p1.x - p2.x)) AS shortest 12 | FROM 13 | point p1 14 | JOIN 15 | point p2 ON p1.x != p2.x 16 | ; 17 | -------------------------------------------------------------------------------- /619. Biggest Single Number.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select max(num) as num 3 | from (select num,count(num) as count from my_numbers group by num) t 4 | where count=1 5 | -------------------------------------------------------------------------------- /620. Not Boring Movies.sql: -------------------------------------------------------------------------------- 1 | select * from cinema 2 | where description <>'boring' and (id%2)>0 3 | order by rating desc 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Leetcode---Database 2 | LeetCode DataBase Answer; mySQL; MS SQL 3 | --------------------------------------------------------------------------------