├── .gitignore ├── README.md ├── datalemur ├── alibaba-compressed-mode.sql ├── frequently-purchased-pairs.sql ├── histogram-users-purchases.sql ├── international-call-percentage.sql ├── laptop-mobile-viewership.sql ├── matching-skills.sql ├── odd-even-measurements.sql ├── repeated-payments.sql ├── rolling-average-tweets.sql ├── signup-confirmation-rate.sql ├── sql-avg-review-ratings.sql ├── sql-highest-grossing.sql ├── sql-page-with-no-likes.sql ├── sql-third-transaction.sql ├── sql-top-three-salaries.sql ├── supercloud-customer.sql ├── time-spent-snaps.sql ├── top-fans-rank.sql └── yoy-growth-rate.sql ├── hackerrank ├── EmployeeEarnings.sql ├── JapaneseCities.sql ├── MoreThan75Marks.sql ├── ThePads.sql ├── WeatherStations8.sql ├── WeatherStations9.sql └── binary-serach-tree1.sql ├── leetcode ├── ConsecutiveNumbers.sql ├── CustomersDontOrder.sql ├── DeptHighestSalary.sql ├── DuplicateEmails.sql ├── HumanTrafficStadium.sql ├── NthHighestSalary.sql ├── RankScores.sql ├── RisingTemperatures.sql ├── SecondHighestSalary.sql ├── Top3DeptSalaries.sql ├── capital-gainloss.sql ├── class5students.sql ├── confirmation-rate.sql ├── employees_managers.sql ├── exchange-seats.sql ├── friend-requests-ii-who-has-the-most-friends.sql ├── game-play-analysis-i.sql ├── game-play-analysis-iv.sql ├── investments-in-2016.sql ├── managers-with-at-least-5-direct-reports.sql ├── market-analysis-i.sql ├── monthly-transactions-i.sql ├── notboringmovies.sql ├── odd-and-event-transactions.sql ├── restaurant-growth.sql ├── tree-node.sql └── trips_and_users.sql └── sqlzoo ├── BiggerThanEurope.sql ├── BusyYearsJohnTravolta.sql ├── NeighborsOfArgentinaAndAustralia.sql ├── RicherThanUK.sql └── TeamsThatHaveCoach.sql /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Practice SQL Scripts From Interview Prep Websites 2 | ------------ 3 | 4 | These are scripts that answer questions from leetcode, DataLemur, hackerank and sqlzoo. Links to questions and my answers are below! 5 | 6 | 7 | ## LeetCode 8 | ----------- 9 | 10 | | Question | Answer | 11 | |-------------------------|------------------------:| 12 | | Employees earn more than their managers | Solution | 13 | | Second highest salaries | Solution | 14 | | Customers who never order | Solution | 15 | | Duplicate Emails | Solution | 16 | |[Rising Temperatures](https://leetcode.com/problems/rising-temperature) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/RisingTemperatures.sql) | 17 | |[Department Top Three Salaries](https://leetcode.com/problems/department-top-three-salaries/submissions/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/Top3DeptSalaries.sql) | 18 | |[N-th Highest Salary](https://leetcode.com/problems/nth-highest-salary/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/NthHighestSalary.sql)| 19 | |[Department Highest Salary](https://leetcode.com/problems/department-highest-salary/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/DeptHighestSalary.sql) | 20 | | [Monthly Transactions I](https://leetcode.com/problems/monthly-transactions-i/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/monthly-transactions-i.sql) | 21 | | [Managers with at Least 5 Direct Reports](https://leetcode.com/problems/managers-with-at-least-5-direct-reports/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/managers-with-at-least-5-direct-reports.sql) | 22 | | [Rank Scores](https://leetcode.com/problems/rank-scores/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/RankScores.sql) | 23 | | [Not Boring Movies](https://leetcode.com/problems/not-boring-movies/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/notboringmovies.sql)| 24 | | [Exchange Seats](https://leetcode.com/problems/exchange-seats/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/exchange-seats.sql)| 25 | | [Consecutive Numbers](https://leetcode.com/problems/consecutive-numbers/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/ConsecutiveNumbers.sql)| 26 | | [Human Traffice Of Stadium](https://leetcode.com/problems/human-traffic-of-stadium/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/HumanTrafficStadium.sql) | 27 | | [Trips and Users](https://leetcode.com/problems/trips-and-users/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/trips_and_users.sql) | 28 | |[Capital Gains/Loss](https://leetcode.com/problems/capital-gainloss/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/capital-gainloss.sql) | 29 | |[Market Analysis I](https://leetcode.com/problems/market-analysis-i/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/market-analysis-i.sql) | 30 | |[Tree Node](https://leetcode.com/problems/tree-node/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/tree-node.sql) | 31 | | [Restaurant Growth](https://leetcode.com/problems/restaurant-growth/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/restaurant-growth.sql) | 32 | | [Game Play Analysis I](https://leetcode.com/problems/game-play-analysis-i/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/game-play-analysis-i.sql) | 33 | | [Game Play Analysis IV](https://leetcode.com/problems/game-play-analysis-iv/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/game-play-analysis-iv.sql) | 34 | | [Investments In 2016](https://leetcode.com/problems/investments-in-2016/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/investments-in-2016.sql) | 35 | | [Friend Requests II: Who Has the Most Friends](https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/description/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/friend-requests-ii-who-has-the-most-friends.sql)| 36 | | [Odd And Even Transactions](https://leetcode.com/problems/odd-and-even-transactions/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/odd-and-event-transactions.sql) | 37 | | [Confirmation Rate](https://leetcode.com/problems/confirmation-rate/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/leetcode/confirmation-rate.sql) | 38 | 39 | 40 | 41 | 42 | ## DataLemur 43 | --------------- 44 | | Question | Answer | 45 | |-------------------------|------------------------:| 46 | |[Laptop vs. Mobile Viewership](https://datalemur.com/questions/laptop-mobile-viewership/) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/laptop-mobile-viewership.sql) | 47 | |[Average Review Ratings](https://datalemur.com/questions/sql-avg-review-ratings) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/sql-avg-review-ratings.sql) | 48 | |[Matching Skills](https://datalemur.com/questions/matching-skills) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/matching-skills.sql) | 49 | | [Odd and Even Measurements](https://datalemur.com/questions/odd-even-measurements) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/odd-even-measurements.sql) | 50 | | [Y-on-Y Growth Rate](https://datalemur.com/questions/yoy-growth-rate) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/yoy-growth-rate.sql) | 51 | | [Page With No Likes](https://datalemur.com/questions/sql-page-with-no-likes) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/sql-page-with-no-likes.sql) | 52 | | [Frequently Purchased Pairs](https://datalemur.com/questions/frequently-purchased-pairs) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/frequently-purchased-pairs.sql) | 53 | | [Supercloud Customer](https://datalemur.com/questions/supercloud-customer) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/supercloud-customer.sql) | 54 | | [Sending vs. Opening Snap](https://datalemur.com/questions/time-spent-snaps) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/time-spent-snaps.sql) | 55 | | [User's Third Transaction](https://datalemur.com/questions/sql-third-transaction) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/sql-third-transaction.sql) | 56 | | [Repeated Payments](https://datalemur.com/questions/repeated-payments) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/repeated-payments.sql) | 57 | | [Compressed Mode](https://datalemur.com/questions/alibaba-compressed-mode) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/alibaba-compressed-mode.sql) | 58 | | [Signup Activation Rate](https://datalemur.com/questions/signup-confirmation-rate) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/signup-confirmation-rate.sql) | 59 | | [Highest-Grossing Items](https://datalemur.com/questions/sql-highest-grossing) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/sql-highest-grossing.sql) | 60 | | [Top 5 Artists](https://datalemur.com/questions/top-fans-rank.sql) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/top-fans-rank.sql) | 61 | | [International Call Percentage](https://datalemur.com/questions/international-call-percentage) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/international-call-percentage.sql) | 62 | | [Tweets' Rolling Average](https://datalemur.com/questions/rolling-average-tweets) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/rolling-average-tweets.sql) | 63 | | [Top Three Salaries](https://datalemur.com/questions/sql-top-three-salaries) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/sql-top-three-salaries.sql) | 64 | | [Histogram of Users and Purchases](https://datalemur.com/questions/histogram-users-purchases) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/datalemur/histogram-users-purchases.sql) | 65 | 66 | 67 | 68 | 69 | 70 | ## Hacker Rank 71 | --------------- 72 | 73 | | Question | Answer | 74 | |-------------------------|------------------------:| 75 | | [Japanese Cities](https://www.hackerrank.com/challenges/japanese-cities-attributes/problem) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/hackerrank/JapaneseCities.sql) | 76 | | Earnings of employees | Solution | 77 | | [Weather Observation Station 8](https://www.hackerrank.com/challenges/weather-observation-station-8/problem) | [Soluton](https://github.com/mdh266/SQL-Practice/blob/master/hackerrank/WeatherStation8.sql) | 78 | | [Weather Observation Station 9](https://www.hackerrank.com/challenges/weather-observation-station-9/problem) | [Soluton](https://github.com/mdh266/SQL-Practice/blob/master/hackerrank/WeatherStation9.sql) | 79 | | [More Than 75 Marks](https://www.hackerrank.com/challenges/more-than-75-marks/problem) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/hackerrank/MoreThan75Marks.sql) | 80 | | [The Pads](https://www.hackerrank.com/challenges/the-pads/problem) | [Solution](https://github.com/mdh266/SQL-Practice/blob/master/hackerrank/ThePads.sql) | 81 | | [Binary Search Tree 1](https://www.hackerrank.com/challenges/binary-search-tree-1/)| [Solution](https://github.com/mdh266/SQL-Practice/blob/master/hackerrank/binary-serach-tree1.sql) | 82 | 83 | 84 | 85 | ## SQLZoo 86 | ------------ 87 | 88 | | Question | Answer | 89 | |-------------------------|------------------------:| 90 | | Richer Than UK | Solution | 91 | | Bigger Than Every Country In Europe | Solution | 92 | | Neighbours of Argentina and Australia | Solution | 93 | | Teams that have coach Fernando Santos | Solution | 94 | | Busy years for John Travolta | Solution | 95 | -------------------------------------------------------------------------------- /datalemur/alibaba-compressed-mode.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | item_count 3 | FROM ( 4 | SELECT 5 | item_count, 6 | DENSE_RANK() OVER(ORDER BY order_occurrences DESC) AS rnk 7 | FROM 8 | items_per_order 9 | ) BASE 10 | WHERE rnk = 1 11 | ORDER BY 1 12 | ; -------------------------------------------------------------------------------- /datalemur/frequently-purchased-pairs.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | COUNT(DISTINCT(product_pairs)) 3 | FROM ( 4 | SELECT 5 | transaction_id, 6 | ARRAY_AGG(product_id) AS product_pairs 7 | FROM 8 | transactions 9 | GROUP BY transaction_id 10 | ) BASE 11 | WHERE 12 | ARRAY_LENGTH(product_pairs,1) > 1 13 | ; -------------------------------------------------------------------------------- /datalemur/histogram-users-purchases.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | transaction_date, 3 | user_id, 4 | SUM(transaction_count) OVER( 5 | PARTITION BY user_id 6 | ORDER BY transaction_date DESC 7 | ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 8 | ) AS purchase_count 9 | FROM ( 10 | SELECT 11 | user_id, 12 | transaction_date, 13 | count(1) AS transaction_count, 14 | RANK() OVER( 15 | PARTITION BY user_id 16 | ORDER BY transaction_date DESC 17 | ) AS transaction_rank 18 | FROM 19 | user_transactions 20 | GROUP BY 1,2 21 | ) T 22 | WHERE 23 | T.transaction_rank = 1 24 | ORDER BY 1 ASC 25 | ; -------------------------------------------------------------------------------- /datalemur/international-call-percentage.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | ROUND( 3 | 100 * SUM(CASE WHEN base.caller_country_id != R.country_id 4 | THEN 1 5 | ELSE 0 END)::NUMERIC / COUNT(*)::NUMERIC, 1) 6 | AS international_calls_pct 7 | FROM ( 8 | SELECT 9 | L.caller_id, 10 | R.country_id AS caller_country_id, 11 | L.receiver_id 12 | FROM 13 | phone_calls AS L 14 | LEFT JOIN 15 | phone_info AS R 16 | ON 17 | L.caller_id = R.caller_id 18 | ) AS base 19 | LEFT JOIN 20 | phone_info AS R 21 | ON 22 | base.receiver_id = R.caller_id 23 | -------------------------------------------------------------------------------- /datalemur/laptop-mobile-viewership.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | SUM(CASE WHEN device_type = 'laptop' THEN 1 ELSE 0 END) AS laptop_views, 3 | SUM(CASE WHEN device_type != 'laptop' THEN 1 ELSE 0 END) AS mobile_views 4 | FROM 5 | viewership -------------------------------------------------------------------------------- /datalemur/matching-skills.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | candidate_id 3 | FROM ( 4 | SELECT 5 | candidate_id, 6 | ARRAY_AGG(skill) AS skills 7 | FROM 8 | candidates 9 | GROUP BY 1 10 | ) A 11 | WHERE 12 | 'Python'=ANY(skills) 13 | AND 14 | 'Tableau'=ANY(skills) 15 | AND 16 | 'PostgreSQL'=ANY(skills) 17 | ; -------------------------------------------------------------------------------- /datalemur/odd-even-measurements.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | measurement_day, 3 | SUM(CASE WHEN day_rnk % 2 != 0 THEN measurement_value ELSE 0 END) odd_sum, 4 | SUM(CASE WHEN day_rnk % 2 = 0 THEN measurement_value ELSE 0 END) even_sum 5 | FROM ( 6 | SELECT 7 | measurement_time::DATE AS measurement_day, 8 | measurement_value, 9 | ROW_NUMBER() OVER( 10 | PARTITION BY measurement_time::DATE 11 | ORDER BY measurement_time ASC 12 | ) AS day_rnk 13 | FROM 14 | measurements 15 | ) BASE 16 | GROUP BY 1 17 | ; -------------------------------------------------------------------------------- /datalemur/repeated-payments.sql: -------------------------------------------------------------------------------- 1 | 2 | -- Create cartesian and compare every transaction of same merchent, card, and amount to one another 3 | -- and get the time between the transcations 4 | WITH crossjoin AS ( 5 | SELECT 6 | L.merchant_id, 7 | L.credit_card_id, 8 | L.amount, 9 | ABS(EXTRACT(MINS FROM L.transaction_timestamp - R.transaction_timestamp)) AS diff 10 | FROM 11 | transactions AS L 12 | LEFT JOIN 13 | transactions AS R 14 | ON ( 15 | L.merchant_id = R.merchant_id 16 | AND 17 | L.credit_card_id = R.credit_card_id 18 | AND 19 | L.amount = R.amount) 20 | ) 21 | 22 | SELECT 23 | COUNT(1) payment_count 24 | FROM ( 25 | SELECT 26 | merchant_id, 27 | credit_card_id, 28 | amount, 29 | row_number() OVER(PARTITION BY merchant_id, credit_card_id, amount, diff ORDER BY diff ASC) AS TXN_NUM 30 | FROM 31 | crossjoin 32 | WHERE 33 | 0 < diff -- Exclude comparing transaction to self 34 | AND 35 | diff < 10 -- within 10 minutes 36 | ) BASE 37 | WHERE 38 | TXN_NUM != 1 -- exclude the first one since doesnt count as repeated transaction 39 | 40 | -------------------------------------------------------------------------------- /datalemur/rolling-average-tweets.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | user_id, 3 | tweet_date, 4 | ROUND( 5 | AVG(tweet_count) OVER (PARTITION BY user_id ORDER BY tweet_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 6 | 2 7 | ) AS rolling_avg_3days 8 | FROM 9 | tweets; -------------------------------------------------------------------------------- /datalemur/signup-confirmation-rate.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | ROUND(SUM(sign_up) / COUNT(1), 2) 3 | FROM ( 4 | SELECT 5 | L.user_id, 6 | SUM(CASE WHEN R.signup_action = 'Confirmed' THEN 1 ELSE 0 END) AS sign_up 7 | FROM 8 | emails AS L 9 | LEFT JOIN 10 | texts AS R 11 | ON 12 | L.email_id = R.email_id 13 | GROUP BY 1 14 | ) T 15 | ; -------------------------------------------------------------------------------- /datalemur/sql-avg-review-ratings.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | EXTRACT(MONTH FROM submit_date) AS mth, 3 | product_id AS product, 4 | ROUND(AVG(stars), 2) AS avg_stars 5 | FROM 6 | reviews 7 | GROUP BY 1, 2 8 | ORDER BY 1, 2 9 | ; -------------------------------------------------------------------------------- /datalemur/sql-highest-grossing.sql: -------------------------------------------------------------------------------- 1 | WITH ranked_products AS ( 2 | SELECT 3 | category, 4 | product, 5 | total_spend, 6 | RANK() OVER(PARTITION BY category ORDER BY total_spend DESC) AS rnk 7 | FROM ( 8 | SELECT 9 | category, 10 | product, 11 | SUM(spend) AS total_spend 12 | FROM 13 | product_spend 14 | WHERE 15 | EXTRACT(YEAR FROM transaction_date) = 2022 16 | GROUP BY 1, 2 17 | ) BASE 18 | ) 19 | 20 | SELECT 21 | category, 22 | product, 23 | total_spend 24 | FROM 25 | ranked_products 26 | WHERE 27 | rnk <= 2 28 | ORDER BY 1 ASC,3 DESC 29 | ; -------------------------------------------------------------------------------- /datalemur/sql-page-with-no-likes.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | L.page_id 3 | FROM 4 | pages AS L 5 | LEFT JOIN 6 | page_likes AS R 7 | ON 8 | L.page_id = R.page_id 9 | WHERE 10 | R.liked_date IS NULL 11 | ORDER BY 12 | page_id 13 | ; -------------------------------------------------------------------------------- /datalemur/sql-third-transaction.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | user_id, 3 | spend, 4 | transaction_date 5 | FROM ( 6 | SELECT 7 | user_id, 8 | spend, 9 | transaction_date, 10 | ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY transaction_date ASC) AS trans_rank 11 | FROM 12 | transactions 13 | ) base 14 | WHERE 15 | base.trans_rank = 3 16 | ; -------------------------------------------------------------------------------- /datalemur/sql-top-three-salaries.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | D.department_name, 3 | E.name, 4 | E.salary 5 | FROM ( 6 | SELECT 7 | name, 8 | salary, 9 | department_id, 10 | DENSE_RANK() OVER(PARTITION BY department_id ORDER BY salary DESC) AS salary_rank 11 | FROM 12 | employee 13 | ) AS e 14 | JOIN 15 | department AS D 16 | ON 17 | E.department_id = D.department_id 18 | WHERE 19 | salary_rank <= 3 20 | ORDER BY 21 | department_name ASC, 22 | salary DESC, 23 | name ASC 24 | ; 25 | 26 | -------------------------------------------------------------------------------- /datalemur/supercloud-customer.sql: -------------------------------------------------------------------------------- 1 | WITH cat_combos AS ( 2 | SELECT 3 | L.customer_id, 4 | R.product_category 5 | FROM 6 | customer_contracts AS L 7 | LEFT JOIN 8 | products AS R 9 | ON 10 | L.product_id = R.product_id 11 | GROUP BY 1, 2 12 | ) 13 | 14 | 15 | SELECT 16 | customer_id 17 | FROM ( 18 | SELECT 19 | customer_id, 20 | COUNT(1) AS category_ct 21 | FROM 22 | cat_combos 23 | GROUP BY 1 24 | HAVING COUNT(1) = (SELECT COUNT(DISTINCT(product_category)) FROM products) 25 | ) base 26 | 27 | -------------------------------------------------------------------------------- /datalemur/time-spent-snaps.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | R.age_bucket, 3 | ROUND(100 * SUM(CASE WHEN L.activity_type = 'send' 4 | THEN L.time_spent 5 | ELSE 0 END) / SUM(time_spent), 2) AS send_perc, 6 | ROUND(100 * SUM(CASE WHEN L.activity_type = 'open' 7 | THEN L.time_spent 8 | ELSE 0 END) / SUM(time_spent), 2) AS open_prec 9 | FROM 10 | activities AS L 11 | JOIN 12 | age_breakdown AS R 13 | ON 14 | L.user_id = R.user_id 15 | WHERE 16 | L.activity_type IN ('open', 'send') 17 | GROUP BY 1 18 | ; -------------------------------------------------------------------------------- /datalemur/top-fans-rank.sql: -------------------------------------------------------------------------------- 1 | WITH artist_counts AS ( 2 | SELECT 3 | artist_name, 4 | COUNT(1) AS ct 5 | FROM ( 6 | SELECT 7 | a.artist_name, 8 | s.song_id 9 | FROM 10 | artists AS a 11 | LEFT JOIN 12 | songs AS s 13 | ON 14 | a.artist_id = s.artist_id 15 | ) AS base 16 | LEFT JOIN 17 | global_song_rank AS g 18 | ON 19 | base.song_id = g.song_id 20 | WHERE 21 | g.rank <= 10 22 | GROUP BY 1 23 | ) 24 | 25 | SELECT 26 | artist_name, 27 | artist_rank 28 | FROM ( 29 | SELECT 30 | artist_name, 31 | DENSE_RANK() OVER (ORDER BY ct DESC) AS artist_rank 32 | FROM 33 | artist_counts 34 | ORDER BY ct DESC 35 | ) base 36 | WHERE artist_rank <= 5 37 | ORDER BY 2 ASC -------------------------------------------------------------------------------- /datalemur/yoy-growth-rate.sql: -------------------------------------------------------------------------------- 1 | WITH product_by_year AS ( 2 | SELECT 3 | year, 4 | product_id, 5 | curr_year_spend, 6 | LAG(curr_year_spend, 1) OVER ( 7 | PARTITION BY product_id ORDER BY YEAR ASC) AS prev_year_spend 8 | FROM ( 9 | SELECT 10 | EXTRACT(YEAR FROM transaction_date) AS year, 11 | product_id, 12 | SUM(spend) AS curr_year_spend 13 | FROM 14 | user_transactions 15 | GROUP BY 16 | product_id, 17 | year 18 | ) BASE 19 | ); 20 | 21 | SELECT 22 | year, 23 | product_id, 24 | curr_year_spend, 25 | prev_year_spend, 26 | ROUND(100 * (curr_year_spend - prev_year_spend ) / prev_year_spend, 2) AS yoy_rate 27 | FROM 28 | product_by_year 29 | ; -------------------------------------------------------------------------------- /hackerrank/EmployeeEarnings.sql: -------------------------------------------------------------------------------- 1 | /* https://www.hackerrank.com/challenges/earnings-of-employees */ 2 | 3 | SELECT months*salary, COUNT(*) 4 | FROM Employee 5 | WHERE months*salary >= 6 | (SELECT MAX(salary * months) 7 | FROM Employee) 8 | -------------------------------------------------------------------------------- /hackerrank/JapaneseCities.sql: -------------------------------------------------------------------------------- 1 | https://www.hackerrank.com/challenges/japanese-cities-attributes/problem 2 | 3 | SELECT * FROM CITY 4 | WHERE CITY.COUNTRYCODE='JPN' 5 | ; -------------------------------------------------------------------------------- /hackerrank/MoreThan75Marks.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | Name 3 | FROM 4 | STUDENTS 5 | WHERE 6 | Marks > 75 7 | ORDER BY 8 | SUBSTR(Name,-3) ASC, 9 | ID ASC 10 | ; -------------------------------------------------------------------------------- /hackerrank/ThePads.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | CONCAT(NAME, '(', SUBSTR(OCCUPATION,1,1), ')') 3 | FROM 4 | OCCUPATIONS 5 | ORDER BY 6 | NAME 7 | ; 8 | SELECT 9 | CONCAT('There are a total of ',CT,' ',LOWER(OCCUPATION),'s.') 10 | FROM ( 11 | SELECT 12 | OCCUPATION, 13 | COUNT(1) AS CT 14 | FROM 15 | OCCUPATIONS 16 | GROUP BY 1 17 | ) COUNTS 18 | ORDER BY 19 | CT ASC, 20 | OCCUPATION ASC 21 | ; -------------------------------------------------------------------------------- /hackerrank/WeatherStations8.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | CITY 3 | FROM 4 | STATION 5 | WHERE 6 | SUBSTR(CITY,1,1) IN ('A','E','I','O','U') 7 | AND 8 | SUBSTR(CITY,-1) IN ('a','e','i','o','u') 9 | GROUP BY 1 10 | ; -------------------------------------------------------------------------------- /hackerrank/WeatherStations9.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | CITY 3 | FROM 4 | STATION 5 | WHERE 6 | SUBSTR(CITY,1,1) IN ('A','E','I','O','U') 7 | GROUP BY 1 8 | ; -------------------------------------------------------------------------------- /hackerrank/binary-serach-tree1.sql: -------------------------------------------------------------------------------- 1 | -- https://www.hackerrank.com/challenges/binary-search-tree-1/ 2 | SELECT 3 | N, 4 | CASE WHEN P IS NULL THEN 'Root' 5 | WHEN C = 'LEAF' THEN 'Leaf' 6 | ELSE 'Inner' 7 | END 8 | FROM ( 9 | SELECT 10 | T1.N, 11 | T1.P, 12 | CASE WHEN T2.N IS NULL THEN 'LEAF' ELSE 'NOT LEAF' END AS C 13 | FROM 14 | BST AS T1 15 | LEFT JOIN 16 | BST AS T2 17 | ON 18 | T2.P = T1.N 19 | GROUP BY N,P,C 20 | ) BASE 21 | GROUP BY 1,2 22 | ORDER BY 1 23 | ; -------------------------------------------------------------------------------- /leetcode/ConsecutiveNumbers.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | Num AS ConsecutiveNums 3 | FROM ( 4 | SELECT 5 | Num, 6 | LAG(Num, 1) OVER(ORDER BY Id ASC) lag1, 7 | LAG(Num, 2) OVER(ORDER BY Id ASC) lag2 8 | FROM 9 | logs 10 | ) LAGS 11 | WHERE 12 | Num - lag1 = 0 13 | AND 14 | Num - lag2 = 0 15 | GROUP BY 1 16 | ; -------------------------------------------------------------------------------- /leetcode/CustomersDontOrder.sql: -------------------------------------------------------------------------------- 1 | /* https://leetcode.com/problems/customers-who-never-order/ */ 2 | 3 | SELECT Name 4 | FROM 5 | (SELECT Name, CustomerId 6 | FROM Customers 7 | LEFT JOIN 8 | Orders 9 | ON (Customers.Id = Orders.CustomerId) 10 | ) Temp 11 | WHERE Temp.CustomerId IS NULL; 12 | 13 | 14 | SELECT name As Customers 15 | FROM Customers 16 | WHERE Customers.Id NOT IN 17 | (SELECT DISTINCT(CustomerId) 18 | FROM Orders) 19 | ; 20 | -------------------------------------------------------------------------------- /leetcode/DeptHighestSalary.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | D.Name AS Department, 3 | E.Name As Employee, 4 | E.Salary 5 | FROM ( 6 | SELECT 7 | Name, 8 | DepartmentId, 9 | Salary, 10 | RANK() OVER(PARTITION BY DepartmentId ORDER BY Salary DESC) rnk 11 | FROM 12 | Employee 13 | ) AS E 14 | JOIN Department As D 15 | ON 16 | E.DepartmentId = D.Id 17 | WHERE 18 | E.rnk = 1 19 | ; -------------------------------------------------------------------------------- /leetcode/DuplicateEmails.sql: -------------------------------------------------------------------------------- 1 | /* https://leetcode.com/problems/duplicate-emails/description/ */ 2 | 3 | SELECT Email 4 | FROM 5 | (SELECT Email, COUNT(Email) AS CNT 6 | FROM Person 7 | GROUP BY Email) 8 | WHERE CNT > 1 9 | 10 | 11 | SELECT Email, COUNT(1) AS ct 12 | FROM Person 13 | GROUP BY 1 14 | HAVING ct > 1 15 | 16 | 17 | select email as Email from Person group by email having count(email)>1 18 | -------------------------------------------------------------------------------- /leetcode/HumanTrafficStadium.sql: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/human-traffic-of-stadium/ 2 | # Write your MySQL query statement below 3 | SELECT 4 | id, 5 | visit_date, 6 | people 7 | FROM ( 8 | SELECT 9 | id, 10 | LAG(id,1) OVER(ORDER BY id ASC) AS lag_id, 11 | LAG(id,2) OVER(ORDER BY id ASC) AS lag2_id, 12 | LEAD(id,1) OVER(ORDER BY id ASC) AS lead_id, 13 | LEAD(id,2) OVER(ORDER BY id ASC) AS lead2_id, 14 | visit_date, 15 | people 16 | FROM 17 | Stadium 18 | WHERE 19 | people >= 100 20 | ) A 21 | WHERE ( 22 | ((id = lead_id - 1) AND (id = lead2_id - 2)) 23 | OR 24 | ((id = lag_id + 1) AND (id = lag2_id + 2)) 25 | OR 26 | ((id = lag_id + 1) AND (id = lead_id - 1)) 27 | ) 28 | ORDER BY 29 | visit_date 30 | -------------------------------------------------------------------------------- /leetcode/NthHighestSalary.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 2 | BEGIN 3 | RETURN ( 4 | # Write your MySQL query statement below. 5 | SELECT 6 | Salary 7 | FROM ( 8 | SELECT 9 | Salary, 10 | DENSE_RANK() OVER(ORDER BY Salary DESC) AS rnk 11 | FROM Employee 12 | ) base 13 | WHERE rnk = N 14 | GROUP BY 1 15 | ); 16 | END -------------------------------------------------------------------------------- /leetcode/RankScores.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | Score as score, 3 | DENSE_RANK() OVER(ORDER BY Score DESC) AS `Rank` 4 | FROM 5 | Scores 6 | ; -------------------------------------------------------------------------------- /leetcode/RisingTemperatures.sql: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/rising-temperature 2 | 3 | SELECT W1.Id 4 | FROM Weather AS W1 5 | LEFT JOIN Weather AS W2 6 | ON DATE_ADD(W2.RecordDate, INTERVAL 1 DAY ) = W1.RecordDate 7 | WHERE W1.Temperature > W2.Temperature 8 | ; 9 | -------------------------------------------------------------------------------- /leetcode/SecondHighestSalary.sql: -------------------------------------------------------------------------------- 1 | /* https://leetcode.com/problems/second-highest-salary/description/ */ 2 | 3 | SELECT MAX(Salary) AS SecondHighestSalary 4 | FROM 5 | Employee E2 6 | WHERE 7 | E2.Salary < 8 | (SELECT MAX(Salary) 9 | FROM 10 | Employee) -------------------------------------------------------------------------------- /leetcode/Top3DeptSalaries.sql: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/department-top-three-salaries/submissions/ 2 | 3 | SELECT 4 | Department, 5 | Employee, 6 | Salary 7 | FROM ( 8 | SELECT 9 | L.Name As Employee, 10 | L.Salary, 11 | R.Name AS Department, 12 | DENSE_RANK() OVER ( 13 | PARTITION BY L.DepartmentId 14 | ORDER BY L.Salary DESC) rnk 15 | FROM 16 | Employee AS L 17 | JOIN 18 | Department AS R 19 | ON 20 | L.DepartmentId = R.Id 21 | ) base 22 | WHERE 23 | base.rnk <= 3 24 | ; -------------------------------------------------------------------------------- /leetcode/capital-gainloss.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | stock_name, 3 | total_sell - total_buy AS capital_gain_loss 4 | FROM ( 5 | SELECT 6 | stock_name, 7 | SUM(CASE WHEN operation = 'Buy' THEN price ELSE 0 END) AS total_buy, 8 | SUM(CASE WHEN operation = 'Sell' THEN price ELSE 0 END) AS total_sell 9 | FROM 10 | Stocks 11 | GROUP BY 1 12 | ) T 13 | ; 14 | 15 | -- or 16 | 17 | SELECT 18 | stock_name, 19 | SUM(CASE WHEN operation = 'Buy' THEN -price 20 | ELSE price 21 | END) AS capital_gain_loss 22 | FROM 23 | Stocks 24 | GROUP BY 1 25 | ; 26 | -------------------------------------------------------------------------------- /leetcode/class5students.sql: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/classes-more-than-5-students 2 | SELECT 3 | class 4 | FROM ( 5 | SELECT 6 | class, 7 | COUNT(1) AS ct 8 | FROM ( 9 | SELECT 10 | class, 11 | student 12 | FROM 13 | courses 14 | GROUP BY 1,2 15 | ) A 16 | GROUP BY 1 17 | ) B 18 | WHERE ct >= 5 19 | ; -------------------------------------------------------------------------------- /leetcode/confirmation-rate.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT 3 | L.user_id, 4 | ROUND( 5 | CAST( 6 | COALESCE( SUM(CASE WHEN R.action = 'confirmed' THEN 1 ELSE 0 END), 0) 7 | AS DOUBLE) / COUNT(1) 8 | , 2) AS confirmation_rate 9 | FROM 10 | Signups AS L 11 | LEFT JOIN 12 | Confirmations AS R 13 | ON 14 | L.user_id = R.user_id 15 | GROUP BY 1 16 | ; -------------------------------------------------------------------------------- /leetcode/employees_managers.sql: -------------------------------------------------------------------------------- 1 | /* https://leetcode.com/problems/employees-earning-more-than-their-managers/description/ */ 2 | SELECT E1.name as Employee 3 | FROM Employee E1 4 | LEFT JOIN Employee E2 5 | ON (E1.ManagerId = E2.Id) 6 | WHERE E1.Salary > E2.Salary; -------------------------------------------------------------------------------- /leetcode/exchange-seats.sql: -------------------------------------------------------------------------------- 1 | 2 | -- Soluton 1, 251 ms 3 | 4 | SELECT 5 | id, 6 | CASE WHEN id % 2 != 0 AND id < (SELECT MAX(id) FROM seat) THEN lead_student 7 | WHEN id % 2 != 0 AND id = (SELECT MAX(id) FROM seat) THEN student 8 | ELSE lag_student 9 | END student 10 | FROM ( 11 | SELECT 12 | id, 13 | LAG(student) OVER (ORDER BY id) AS lag_student, 14 | LEAD(student) OVER (ORDER BY id) AS lead_student, 15 | student 16 | FROM 17 | seat 18 | ) base 19 | ; 20 | 21 | -- Solution 2, 601 ms 22 | SELECT 23 | id, 24 | CASE WHEN MOD(id, 2) = 0 THEN prev_student 25 | WHEN next_id IS NOT NULL THEN next_student 26 | ELSE student 27 | END AS student 28 | FROM ( 29 | SELECT 30 | id, 31 | student, 32 | LAG(student, 1) OVER(ORDER BY id ASC) prev_student, 33 | LEAD(student, 1) OVER(ORDER BY id ASC) next_student, 34 | LEAD(id, 1) OVER(ORDER BY id ASC) next_id 35 | FROM 36 | Seat 37 | ) T 38 | ; 39 | 40 | -- Solution 3, 590ms 41 | 42 | SELECT 43 | CASE WHEN MOD(id, 2) = 0 THEN id - 1 44 | WHEN id < (SELECT MAX(id) FROM Seat) THEN id + 1 45 | ELSE id 46 | END AS id, 47 | student 48 | FROM 49 | Seat 50 | ORDER BY 51 | id ASC 52 | ; -------------------------------------------------------------------------------- /leetcode/friend-requests-ii-who-has-the-most-friends.sql: -------------------------------------------------------------------------------- 1 | 2 | -- COMPLICATED 3 | 4 | SELECT 5 | id, 6 | num 7 | FROM ( 8 | SELECT 9 | COALESCE(L.id, R.id) as id, 10 | COALESCE(requester_cnt,0) + COALESCE(accepter_cnt,0) AS num, 11 | RANK() OVER( ORDER BY COALESCE(requester_cnt,0) + COALESCE(accepter_cnt,0) DESC) AS num_rank 12 | FROM( 13 | SELECT 14 | requester_id AS id, 15 | COUNT(1) AS requester_cnt 16 | FROM 17 | RequestAccepted 18 | GROUP BY 1 19 | ) L 20 | FULL OUTER JOIN 21 | ( SELECT 22 | accepter_id AS id, 23 | COUNT(1) accepter_cnt 24 | FROM 25 | RequestAccepted 26 | GROUP BY 1 27 | ) R 28 | ON 29 | L.id = R.id 30 | ) BASE 31 | WHERE num_rank = 1 32 | ; 33 | 34 | 35 | 36 | 37 | -- SIMPLE 38 | 39 | SELECT 40 | id, 41 | COUNT(1) as num 42 | FROM 43 | (SELECT 44 | requester_id AS id 45 | FROM 46 | RequestAccepted 47 | UNION ALL 48 | SELECT 49 | accepter_id AS id 50 | FROM 51 | RequestAccepted 52 | ) BASE 53 | GROUP BY 1 54 | ORDER BY 2 DESC 55 | LIMIT 1 -------------------------------------------------------------------------------- /leetcode/game-play-analysis-i.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | player_id, 3 | event_date AS first_login 4 | FROM ( 5 | SELECT 6 | player_id, 7 | event_date, 8 | RANK() OVER(PARTITION BY player_id ORDER BY event_date ASC) AS event_rnk 9 | FROM 10 | Activity 11 | ) BASE 12 | WHERE event_rnk = 1 13 | ; -------------------------------------------------------------------------------- /leetcode/game-play-analysis-iv.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | ROUND(COUNT(1) / (SELECT COUNT(DISTINCT(player_id)) FROM Activity), 2) AS fraction 3 | FROM ( 4 | SELECT 5 | player_id, 6 | event_date, 7 | LEAD(event_date, 1) OVER ( 8 | PARTITION BY player_id 9 | ORDER BY event_date ASC) AS next_event, 10 | RANK() OVER ( 11 | PARTITION BY player_id 12 | ORDER BY event_date ASC) AS event_rank 13 | FROM 14 | Activity 15 | ) T 16 | WHERE 17 | event_rank = 1 18 | AND 19 | DATEDIFF(next_event, event_date) = 1 20 | ; -------------------------------------------------------------------------------- /leetcode/investments-in-2016.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | ROUND(SUM(tiv_2016), 2) AS tiv_2016 3 | FROM ( 4 | SELECT 5 | tiv_2016, 6 | COUNT(1) OVER(PARTITION BY tiv_2015) AS tiv_2015_ct, 7 | COUNT(1) OVER(PARTITION BY lat, lon) AS lat_lon_ct 8 | FROM 9 | Insurance 10 | ) T 11 | WHERE 12 | tiv_2015_ct > 1 13 | AND 14 | lat_lon_ct = 1 15 | ; -------------------------------------------------------------------------------- /leetcode/managers-with-at-least-5-direct-reports.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | name 3 | FROM ( 4 | SELECT 5 | L.id, 6 | L.name 7 | FROM 8 | Employee AS L 9 | LEFT JOIN 10 | Employee AS R 11 | ON 12 | L.id = R.managerId 13 | GROUP BY 1,2 14 | HAVING 15 | COUNT(1) >= 5 16 | ) base 17 | ; -------------------------------------------------------------------------------- /leetcode/market-analysis-i.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | L.user_id AS buyer_id, 3 | L.join_date, 4 | COALESCE(R.orders_in_2019, 0) orders_in_2019 5 | FROM 6 | Users AS L 7 | LEFT JOIN ( 8 | SELECT 9 | buyer_id, 10 | COUNT(1) AS orders_in_2019 11 | FROM 12 | Orders 13 | WHERE 14 | YEAR(order_date) = 2019 15 | GROUP BY 1 16 | ) R 17 | ON 18 | L.user_id = R.buyer_id 19 | GROUP BY 1, 2 20 | ; -------------------------------------------------------------------------------- /leetcode/monthly-transactions-i.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | CAST(trans_date AS CHAR(7)) AS month, 3 | country, 4 | COUNT(1) AS trans_count, 5 | SUM(CASE WHEN state = 'approved' THEN 1 ELSE 0 END) approved_count, 6 | SUM(amount) AS trans_total_amount, 7 | SUM(CASE WHEN state = 'approved' THEN amount ELSE 0 END) approved_total_amount 8 | FROM 9 | Transactions 10 | GROUP BY 1,2 11 | ; -------------------------------------------------------------------------------- /leetcode/notboringmovies.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | id, 3 | movie, 4 | description, 5 | rating 6 | FROM 7 | cinema 8 | WHERE 9 | (id % 2 = 1) 10 | AND 11 | (description != 'boring') 12 | ORDER BY 13 | rating DESC 14 | ; -------------------------------------------------------------------------------- /leetcode/odd-and-event-transactions.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | transaction_date, 3 | SUM(CASE WHEN amount % 2 = 1 THEN amount ELSE 0 END) AS odd_sum, 4 | SUM(CASE WHEN amount % 2 = 0 THEN amount ELSE 0 END) AS even_sum 5 | FROM 6 | transactions 7 | GROUP BY 1 8 | ORDER BY 1 ASC 9 | ; -------------------------------------------------------------------------------- /leetcode/restaurant-growth.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | WITH daily_amounts AS ( 3 | SELECT 4 | visited_on, 5 | SUM(amount) AS amount 6 | FROM 7 | Customer 8 | GROUP BY 9 | visited_on 10 | ) 11 | 12 | 13 | SELECT 14 | visited_on, 15 | amount, 16 | ROUND(amount/7, 2) AS average_amount 17 | FROM ( 18 | SELECT 19 | visited_on, 20 | SUM(amount) OVER( 21 | ORDER BY visited_on 22 | RANGE INTERVAL 6 DAY PRECEDING) AS amount 23 | FROM 24 | daily_amounts 25 | ) base 26 | WHERE 27 | DATEDIFF(visited_on, (SELECT MIN(visited_on) FROM daily_amounts)) >= 6 28 | -------------------------------------------------------------------------------- /leetcode/tree-node.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | id, 3 | CASE WHEN child_ct = 0 AND type = "Not Root" THEN "Leaf" 4 | WHEN child_ct > 0 AND type = "Not Root" THEN 'Inner' 5 | ELSE type 6 | END AS type 7 | FROM ( 8 | SELECT 9 | L.id, 10 | CASE WHEN L.p_id IS NULL THEN 'Root' ELSE 'Not Root' END AS type, 11 | SUM(CASE WHEN R.id IS NULL THEN 0 ELSE 1 END) AS child_ct 12 | From 13 | Tree AS L 14 | LEFT JOIN 15 | Tree AS R 16 | ON 17 | L.id = R.p_id 18 | GROUP BY 1,2 19 | ) Base 20 | ; -------------------------------------------------------------------------------- /leetcode/trips_and_users.sql: -------------------------------------------------------------------------------- 1 | -- https://leetcode.com/problems/trips-and-users/submissions/ 2 | 3 | 4 | # Write your MySQL query statement below 5 | SELECT 6 | L.request_at AS Day, 7 | ROUND(SUM(CASE WHEN L.status != 'completed' THEN 1 ELSE 0 END) /COUNT(1),2) AS 'Cancellation Rate' 8 | FROM 9 | Trips AS L 10 | JOIN 11 | ( SELECT 12 | users_id AS client_id 13 | FROM 14 | Users 15 | WHERE 16 | banned = 'No' 17 | AND 18 | role IN ('client') 19 | ) R1 20 | ON 21 | L.client_id = R1.client_id 22 | JOIN ( 23 | SELECT 24 | users_id AS driver_id 25 | FROM 26 | Users 27 | WHERE 28 | role IN ('driver') 29 | AND 30 | banned = 'No' 31 | ) R2 32 | ON 33 | L.driver_id = R2.driver_id 34 | WHERE 35 | request_at BETWEEN '2013-10-01' AND '2013-10-03' 36 | GROUP BY 1 37 | ; 38 | 39 | -------------------------------------------------------------------------------- /sqlzoo/BiggerThanEurope.sql: -------------------------------------------------------------------------------- 1 | SELECT name 2 | FROM world 3 | WHERE gdp > 4 | (SELECT 5 | MAX(gdp) 6 | FROM world 7 | WHERE continent LIKE 'Europe') -------------------------------------------------------------------------------- /sqlzoo/BusyYearsJohnTravolta.sql: -------------------------------------------------------------------------------- 1 | SELECT yr,COUNT(title) 2 | FROM movie 3 | JOIN casting 4 | ON movie.id=movieid 5 | JOIN actor 6 | ON actorid=actor.id 7 | where name='John Travolta' 8 | GROUP BY yr 9 | HAVING COUNT(title)= 10 | (SELECT MAX(c) 11 | FROM 12 | (SELECT yr,COUNT(title) AS c 13 | FROM movie 14 | JOIN casting 15 | ON movie.id=movieid 16 | JOIN actor 17 | ON actorid=actor.id 18 | WHERE name='John Travolta' 19 | GROUP BY yr) AS t 20 | ) -------------------------------------------------------------------------------- /sqlzoo/NeighborsOfArgentinaAndAustralia.sql: -------------------------------------------------------------------------------- 1 | SELECT name, continent 2 | FROM world 3 | WHERE continent LIKE 4 | (SELECT continent FROM world WHERE name LIKE 'Argentina') 5 | OR 6 | continent LIKE 7 | (SELECT continent FROM world WHERE name LIKE 'Australia') 8 | ORDER BY name -------------------------------------------------------------------------------- /sqlzoo/RicherThanUK.sql: -------------------------------------------------------------------------------- 1 | SELECT name 2 | FROM world 3 | WHERE continent LIKE 'Europe' 4 | AND gdp / population > 5 | (SELECT gdp / population 6 | FROM world 7 | WHERE name LIKE 'United Kingdom') -------------------------------------------------------------------------------- /sqlzoo/TeamsThatHaveCoach.sql: -------------------------------------------------------------------------------- 1 | /* http://sqlzoo.net/wiki/The_JOIN_operation */ 2 | 3 | SELECT game.mdate, eteam.teamname 4 | FROM game 5 | JOINeteam 6 | ON (game.team1 = eteam.id) 7 | WHERE eteam.coach like 'Fernando Santos' 8 | --------------------------------------------------------------------------------