├── 1045-Customers-Who-Bought-All-Products.tsql ├── 1068-Product-Sales-Analysis-I.tsql ├── 1070-Product-Sales-Analysis-III.tsql ├── 1075-Project-Employees-I.tsql ├── 1141-User-Activity-for-the-Past-30-Days-I.tsql ├── 1148-Article-Views-I.tsql ├── 1164-Product-Price-at-a-Given-Date.tsql ├── 1174-Immediate-Food-Delivery-II.tsql ├── 1193-Monthly-Transactions-I.tsql ├── 1204-Last-Person-to-Fit-in-the-Bus.tsql ├── 1211-Queries-Quality-and-Percentage.tsql ├── 1251-Average-Selling-Price.tsql ├── 1280-Students-and-Examinations.tsql ├── 1321-Restaurant-Growth.tsql ├── 1327-List-the-Products-Ordered-in-a-Period.tsql ├── 1341-Movie-Rating.tsql ├── 1378-Replace-Employee-ID-With-The-Unique-Identifier.tsql ├── 1484-Group-Sold-Products-By-The-Date.tsql ├── 1517-Find-Users-With-Valid-E-Mails.tsql ├── 1527-Patients-With-a-Condition.tsql ├── 1581-Customer-Who-Visited-but-Did-Not-Make-Any-Transactions.tsql ├── 1633-Percentage-of-Users-Attended-a-Contest.tsql ├── 1661-Average-Time-of-Process-per-Machine.tsql ├── 1667-Fix-Names-in-a-Table.tsql ├── 1683-Invalid-Tweets.tsql ├── 1729-Find-Followers-Count.sql ├── 1731-The-Number-of-Employees-Which-Report-to-Each-Employee.tsql ├── 1757-Recyclable-and-Low-Fat-Products.sql ├── 176-Second-Highest-Salary.tsql ├── 1768-Merge-Strings-Alternately.cs ├── 1789-Primary-Department-for-Each-Employee.tsql ├── 180-Consecutive-Numbers.tsql ├── 185-Department-Top-Three-Salaries.tsql ├── 1907-Count-Salary-Categories.tsql ├── 1934-Confirmation-Rate.tsql ├── 196-Delete-Duplicate-Emails.tsql ├── 197-Rising-Temperature.tsql ├── 1978-Employees-Whose-Manager-Left-the-Company.tsql ├── 2356-Number-of-Unique-Subjects-Taught-by-Each-Teacher.tsql ├── 550-Game-Play-Analysis-IV.tsql ├── 570-Managers-with-at-Least-5-Direct-Reports.tsql ├── 577-Employee-Bonus.tsql ├── 584-Find-Customer-Referee.sql ├── 585-Investments-in-2016.tsql ├── 595-Big-Countries.tsql ├── 596-Classes-More-Than-5-Students.sql ├── 602-Friend-Requests-II:-Who-Has-the-Most-Friends.tsql ├── 610-Triangle-Judgement.tsql ├── 619-Biggest-Single-Number.tsql ├── 620-Not-Boring-Movies.tsql ├── 626-Exchange-Seats.tsql └── README.md /1045-Customers-Who-Bought-All-Products.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | /* 3 | 4 | 5 | WITH TotalProducts AS( 6 | SELECT 7 | COUNT(product_key) AS number_of_products 8 | FROM Product 9 | ), 10 | CustomerProductCount AS( 11 | SELECT customer_id, 12 | COUNT(DISTINCT product_key) AS number_of_uniqe_proudects_for_each_user 13 | FROM Customer 14 | GROUP BY customer_id 15 | ) 16 | SELECT cpc.customer_id 17 | FROM CustomerProductCount cpc 18 | JOIN TotalProducts 19 | ON number_of_products = number_of_uniqe_proudects_for_each_user 20 | 21 | 22 | */ 23 | 24 | -- simple solution 25 | 26 | 27 | SELECT 28 | customer_id 29 | FROM 30 | Customer 31 | GROUP BY 32 | customer_id 33 | HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(product_key) FROM Product) 34 | 35 | -------------------------------------------------------------------------------- /1068-Product-Sales-Analysis-I.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | select p.product_name ,s.year ,s.price from sales s 3 | join product p on p.product_id = s.product_id -------------------------------------------------------------------------------- /1070-Product-Sales-Analysis-III.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH FirstSales AS( 3 | SELECT 4 | *, 5 | RANK() OVER(PARTITION BY product_id ORDER BY year) AS rnk 6 | FROM Sales 7 | ) 8 | SELECT product_id, 9 | year as first_year, 10 | quantity, 11 | price 12 | FROM FirstSales 13 | WHERE rnk = 1 -------------------------------------------------------------------------------- /1075-Project-Employees-I.tsql: -------------------------------------------------------------------------------- 1 | SELECT 2 | p.project_id, 3 | ROUND(AVG(e.experience_years * 1.0), 2) AS average_years 4 | FROM Project p 5 | JOIN Employee e ON p.employee_id = e.employee_id 6 | GROUP BY p.project_id; 7 | -------------------------------------------------------------------------------- /1141-User-Activity-for-the-Past-30-Days-I.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | -- i need to calc num of unique users that open between 2019-07-27 and -29 day befor group by day 3 | 4 | SELECT activity_date AS 'day' , 5 | COUNT(DISTINCT user_id) AS active_users 6 | FROM Activity 7 | WHERE activity_date BETWEEN DATEADD( day, -29,'2019-07-27') AND '2019-07-27' 8 | GROUP BY activity_date -------------------------------------------------------------------------------- /1148-Article-Views-I.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | select distinct author_id as id from views 3 | where author_id = viewer_id 4 | order by id -------------------------------------------------------------------------------- /1164-Product-Price-at-a-Given-Date.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH FirstProduct AS( 3 | SELECT 4 | *, 5 | ROW_NUMBER()OVER(PARTITION BY product_id ORDER BY change_date DESC) AS rn 6 | FROM Products 7 | WHERE change_date <= '2019-08-16' 8 | ) 9 | SELECT p.product_id , 10 | COALESCE(fp.new_price ,10) AS price 11 | FROM (SELECT DISTINCT product_id FROM Products ) p 12 | LEFT JOIN FirstProduct fp 13 | ON p.product_id = fp.product_id AND fp.rn =1 -------------------------------------------------------------------------------- /1174-Immediate-Food-Delivery-II.tsql: -------------------------------------------------------------------------------- 1 | WITH FirstOrderDate AS( 2 | SELECT customer_id , 3 | MIN(order_date) AS first_order_date 4 | FROM Delivery 5 | GROUP BY customer_id 6 | ) 7 | SELECT 8 | ROUND( 9 | SUM(CASE WHEN d.order_date =customer_pref_delivery_date THEN 1 ELSE 0 END ) *100.0 / COUNT(*) 10 | ,2) AS immediate_percentage 11 | FROM Delivery d 12 | JOIN FirstOrderDate f 13 | ON d.order_date = f.first_order_date AND d.customer_id = f.customer_id -------------------------------------------------------------------------------- /1193-Monthly-Transactions-I.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT FORMAT(t.trans_date,'yyyy-MM') AS month, 3 | t.country , 4 | COUNT(*)AS trans_count , 5 | SUM(CASE WHEN t.state = 'approved' THEN 1 ELSE 0 END) AS approved_count , 6 | SUM(amount) AS trans_total_amount , 7 | SUM(CASE WHEN state = 'approved' THEN t.amount ELSE 0 END) AS approved_total_amount 8 | FROM Transactions t 9 | GROUP BY FORMAT(trans_date,'yyyy-MM') , t.country -------------------------------------------------------------------------------- /1204-Last-Person-to-Fit-in-the-Bus.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH SumWights AS( 3 | SELECT * , 4 | SUM(Weight) OVER(ORDER BY Turn) AS my_sum_wight 5 | FROM Queue 6 | ) 7 | SELECT TOP 1 person_name 8 | FROM SumWights 9 | WHERE my_sum_wight <=1000 10 | ORDER BY turn DESC -------------------------------------------------------------------------------- /1211-Queries-Quality-and-Percentage.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT query_name , 3 | ROUND( 4 | AVG(rating * 1.0 / position) 5 | ,2) AS quality , 6 | ROUND( 7 | SUM(CASE WHEN rating < 3 THEN 1 ELSE 0 END) *100.0 / COUNT(query_name) 8 | ,2) AS poor_query_percentage 9 | FROM Queries 10 | WHERE query_name IS NOT NULL 11 | GROUP BY query_name -------------------------------------------------------------------------------- /1251-Average-Selling-Price.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | select p.product_id , 3 | ROUND( 4 | ISNULL( 5 | CAST( 6 | SUM( 7 | p.price * u.units 8 | )as float 9 | ) / NULLIF(SUM(u.units),0) 10 | ,0) 11 | ,2) as average_price 12 | from Prices p 13 | left join UnitsSold u 14 | on p.product_id = u.product_id 15 | AND u.purchase_date BETWEEN p.start_date AND p.end_date 16 | group by p.product_id -------------------------------------------------------------------------------- /1280-Students-and-Examinations.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | select s.student_id , s.student_name ,sub.subject_name, count(e.student_id) as attended_exams 3 | from Students s 4 | cross join Subjects sub 5 | left join Examinations e 6 | on s.student_id = e.student_id 7 | and sub.subject_name = e.subject_name 8 | group by s.student_id , s.student_name ,sub.subject_name -------------------------------------------------------------------------------- /1321-Restaurant-Growth.tsql: -------------------------------------------------------------------------------- 1 | WITH DailyIncome AS( 2 | SELECT visited_on , 3 | SUM(amount) AS daily_amount 4 | FROM Customer 5 | GROUP BY visited_on 6 | ), 7 | AggregatedResults AS( 8 | SELECT visited_on, 9 | SUM(daily_amount) over(ORDER BY visited_on ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)AS amount , 10 | ROW_NUMBER() OVER(ORDER BY visited_on) AS row_num 11 | FROM DailyIncome 12 | ) 13 | SELECT 14 | visited_on, 15 | amount , 16 | ROUND((amount*1.0)/7,2) AS average_amount 17 | FROM AggregatedResults 18 | WHERE row_num >= 7 19 | -------------------------------------------------------------------------------- /1327-List-the-Products-Ordered-in-a-Period.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH SumWights AS( 3 | SELECT * , 4 | SUM(Weight) OVER(ORDER BY Turn) AS my_sum_wight 5 | FROM Queue 6 | ) 7 | SELECT TOP 1 person_name 8 | FROM SumWights 9 | WHERE my_sum_wight <=1000 10 | ORDER BY turn DESC -------------------------------------------------------------------------------- /1341-Movie-Rating.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH UserRatings AS( 3 | SELECT u.name as results , COUNT(mr.user_id) AS user_rateing 4 | FROM Users u 5 | RIGHT JOIN MovieRating mr 6 | ON mr.user_id = u.user_id 7 | GROUP BY u.name 8 | ), 9 | MaxRatingCount AS( 10 | SELECT MAX(user_rateing) AS max_user_rateing FROM UserRatings 11 | ), 12 | MovieAverageRatings AS( 13 | SELECT m.title AS results , AVG(mr.rating*1.0) avg_rateing 14 | FROM Movies m 15 | RIGHT JOIN MovieRating mr 16 | on m.movie_id = mr.movie_id 17 | WHERE YEAR(mr.created_at) = 2020 AND MONTH(mr.created_at)=2 18 | GROUP BY m.title 19 | ), 20 | MaxAverageRating AS( 21 | SELECT MAX(avg_rateing) AS max_avg_rating FROM MovieAverageRatings 22 | ) 23 | SELECT results FROM ( 24 | SELECT TOP 1 results 25 | FROM UserRatings 26 | JOIN MaxRatingCount 27 | ON max_user_rateing = user_rateing 28 | ORDER BY results 29 | ) AS user_queru 30 | 31 | UNION ALL 32 | 33 | SELECT results FROM ( 34 | SELECT TOP 1 results 35 | FROM MovieAverageRatings 36 | JOIN MaxAverageRating 37 | ON avg_rateing = max_avg_rating 38 | ORDER BY results 39 | ) AS movie_queru -------------------------------------------------------------------------------- /1378-Replace-Employee-ID-With-The-Unique-Identifier.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | select eu.unique_id , e.name from EmployeeUNI eu 3 | Right join Employees e ON eu.id = e.id -------------------------------------------------------------------------------- /1484-Group-Sold-Products-By-The-Date.tsql: -------------------------------------------------------------------------------- 1 | WITH unique_products AS ( 2 | SELECT DISTINCT sell_date, product 3 | FROM Activities 4 | ) 5 | SELECT 6 | sell_date, 7 | COUNT(product) as num_sold, 8 | STRING_AGG(product, ',') WITHIN GROUP (ORDER BY product) as products 9 | FROM unique_products 10 | GROUP BY sell_date 11 | ORDER BY sell_date; -------------------------------------------------------------------------------- /1517-Find-Users-With-Valid-E-Mails.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT user_id, name, mail 3 | FROM Users 4 | WHERE mail LIKE '[a-zA-Z]%@leetcode.com' 5 | AND mail NOT LIKE '%[^a-zA-Z0-9._-]%@leetcode.com' -------------------------------------------------------------------------------- /1527-Patients-With-a-Condition.tsql: -------------------------------------------------------------------------------- 1 | SELECT patient_id, patient_name, conditions 2 | FROM Patients 3 | WHERE conditions like 'DIAB1%' 4 | or conditions like '% DIAB1' 5 | or conditions like '% DIAB1%' 6 | -------------------------------------------------------------------------------- /1581-Customer-Who-Visited-but-Did-Not-Make-Any-Transactions.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT V.customer_id, COUNT(*) AS count_no_trans 3 | FROM Visits V 4 | LEFT JOIN Transactions T ON V.visit_id = T.visit_id 5 | WHERE T.visit_id IS NULL 6 | GROUP BY V.customer_id; 7 | -------------------------------------------------------------------------------- /1633-Percentage-of-Users-Attended-a-Contest.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | 3 | WITH TotalUsers AS ( 4 | SELECT COUNT(user_id) AS total_users 5 | FROM Users 6 | ), 7 | TotalUserInOneContest AS( 8 | SELECT contest_id , COUNT(user_id) AS total_user_in_cne_contest 9 | FROM Register 10 | GROUP BY contest_id 11 | ) 12 | SELECT tuc.contest_id , 13 | ROUND( 14 | CAST( 15 | (tuc.total_user_in_cne_contest * 100.0 / tu.total_users) AS FLOAT 16 | ) 17 | ,2) AS percentage 18 | FROM TotalUsers tu 19 | CROSS JOIN TotalUserInOneContest tuc 20 | ORDER BY percentage DESC , tuc.contest_id ASC 21 | 22 | 23 | 24 | -- NOTES 25 | 26 | -- in JOIN there is no ON condtion so i USE CROSS JOIN 27 | -- CTE => WITH TotalUsers AS , ContestRegistrations AS => thos are CTE , is a temp data not store anywhere just on memory you must use your SELECT statement after it direct(or in the seme selected query) becuse if you didnt it will not work cuz its temp 28 | --tuc.total_user_in_cne_contest and tu.total_users are integers, the division operation will perform integer division before multiplying by 100.0 so , 100.0 first not in the end 29 | -- ((tuc.total_user_in_cne_contest / tu.total_users) * 100.0) XXXXXXXXXXXXXXXXX 30 | -- ((tuc.total_user_in_cne_contest * 100.0) / tu.total_users) => true 31 | 32 | -------------------------------------------------------------------------------- /1661-Average-Time-of-Process-per-Machine.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT 3 | a.machine_id, 4 | ROUND(AVG(b.timestamp - a.timestamp), 3) AS processing_time 5 | FROM 6 | Activity a 7 | JOIN 8 | Activity b ON a.machine_id = b.machine_id 9 | AND a.process_id = b.process_id 10 | AND a.activity_type = 'start' 11 | AND b.activity_type = 'end' 12 | GROUP BY 13 | a.machine_id; -------------------------------------------------------------------------------- /1667-Fix-Names-in-a-Table.tsql: -------------------------------------------------------------------------------- 1 | SELECT 2 | user_id, 3 | UPPER(SUBSTRING(name, 1, 1)) + LOWER(SUBSTRING(name, 2, LEN(name) - 1)) AS name 4 | FROM 5 | Users 6 | ORDER BY 7 | user_id; 8 | -------------------------------------------------------------------------------- /1683-Invalid-Tweets.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | select tweet_id from Tweets 3 | where len(content) >15 -------------------------------------------------------------------------------- /1729-Find-Followers-Count.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT user_id , COUNT(follower_id) AS followers_count 3 | FROM Followers 4 | GROUP BY user_id 5 | ORDER BY user_id -------------------------------------------------------------------------------- /1731-The-Number-of-Employees-Which-Report-to-Each-Employee.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT 3 | m.employee_id , 4 | m.name , 5 | COUNT(e.employee_id) AS reports_count, 6 | ROUND(AVG(e.age*1.0),0) AS average_age 7 | FROM Employees e 8 | JOIN Employees m 9 | ON m.employee_id = e.reports_to 10 | GROUP BY m.employee_id , m.name 11 | ORDER BY m.employee_id , m.name 12 | -------------------------------------------------------------------------------- /1757-Recyclable-and-Low-Fat-Products.sql: -------------------------------------------------------------------------------- 1 | -- Write your PostgreSQL query statement below 2 | select product_id from Products 3 | where low_fats ='Y' and recyclable = 'Y' -------------------------------------------------------------------------------- /176-Second-Highest-Salary.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH RankedSalaries AS ( 3 | SELECT salary, 4 | DENSE_RANK() OVER (ORDER BY salary DESC) AS rank 5 | FROM Employee 6 | ) 7 | SELECT 8 | MAX(salary) AS SecondHighestSalary 9 | FROM 10 | RankedSalaries 11 | WHERE 12 | rank = 2; 13 | -------------------------------------------------------------------------------- /1768-Merge-Strings-Alternately.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public string MergeAlternately(string word1, string word2) { 3 | var res = new StringBuilder(); 4 | int minLen = Math.Min(word1.Length, word2.Length); 5 | 6 | for (int i = 0; i < minLen; i++) 7 | { 8 | res.Append(word1[i]); 9 | res.Append(word2[i]); 10 | } 11 | 12 | if (word1.Length > minLen) 13 | res.Append(word1.Substring(minLen)); 14 | else if (word2.Length > minLen) 15 | res.Append(word2.Substring(minLen)); 16 | 17 | return res.ToString(); 18 | } 19 | } -------------------------------------------------------------------------------- /1789-Primary-Department-for-Each-Employee.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH GetYEmps AS ( 3 | SELECT employee_id, department_id 4 | FROM Employee 5 | WHERE primary_flag = 'Y' 6 | ) 7 | SELECT employee_id, department_id 8 | FROM Employee 9 | WHERE primary_flag = 'Y' 10 | OR employee_id NOT IN (SELECT employee_id FROM GetYEmps); 11 | -------------------------------------------------------------------------------- /180-Consecutive-Numbers.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | -- this solve 3 | 4 | -- SELECT DISTINCT l1.num AS ConsecutiveNums 5 | -- FROM Logs l1 6 | -- JOIN Logs l2 ON l1.id = l2.id - 1 7 | -- JOIN Logs l3 ON l1.id = l3.id - 2 8 | -- WHERE l1.num = l2.num and l1.num = l3.num 9 | 10 | -- this anther solve 11 | 12 | WITH cte AS ( 13 | SELECT *, 14 | LAG(num) OVER(ORDER BY id) AS prev_num , 15 | LEAD(num)OVER(ORDER BY id) AS next_num 16 | FROM Logs 17 | ) 18 | SELECT 19 | DISTINCT num AS ConsecutiveNums 20 | FROM cte 21 | WHERE num = prev_num AND num = next_num 22 | -------------------------------------------------------------------------------- /185-Department-Top-Three-Salaries.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH TopThreeSalaries AS( 3 | SELECT d.name AS Department , e.name AS Employee , e.salary AS Salary , 4 | DENSE_RANK()OVER(PARTITION BY d.id ORDER BY e.salary DESC) AS rn 5 | FROM Employee e 6 | LEFT JOIN Department d 7 | ON e.departmentId = d.id 8 | ) 9 | SELECT Department , Employee , Salary 10 | FROM TopThreeSalaries 11 | WHERE rn <= 3 -------------------------------------------------------------------------------- /1907-Count-Salary-Categories.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH GetNumLow AS( 3 | SELECT COUNT(income) AS accounts_count 4 | FROM Accounts 5 | WHERE income < 20000 6 | ), 7 | GetNumAverage AS( 8 | SELECT COUNT(income) AS accounts_count 9 | FROM Accounts 10 | WHERE income BETWEEN 20000 AND 50000 11 | ), 12 | GetNumHigh AS( 13 | SELECT COUNT(income) AS accounts_count 14 | FROM Accounts 15 | WHERE income > 50000 16 | ) 17 | SELECT 'Low Salary' AS category , accounts_count 18 | FROM GetNumLow 19 | UNION ALL 20 | SELECT 'Average Salary' AS category , accounts_count 21 | FROM GetNumAverage 22 | UNION ALL 23 | SELECT 'High Salary' AS category , accounts_count 24 | FROM GetNumHigh -------------------------------------------------------------------------------- /1934-Confirmation-Rate.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | select s.user_id , 3 | ROUND( 4 | ISNULL( 5 | CAST( 6 | SUM( 7 | CASE When c.action = 'confirmed' THEN 1 ELSE 0 8 | END 9 | )as float 10 | ) / NULLIF(count(c.user_id),0) 11 | ,0 12 | ) 13 | ,2) as confirmation_rate 14 | from Signups s 15 | left join Confirmations c 16 | on s.user_id = c.user_id 17 | group by s.user_id -------------------------------------------------------------------------------- /196-Delete-Duplicate-Emails.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | DELETE FROM Person 3 | WHERE ID NOT IN( 4 | SELECT min(id) 5 | FROM Person 6 | GROUP BY email 7 | ) 8 | -------------------------------------------------------------------------------- /197-Rising-Temperature.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT id 3 | FROM ( 4 | SELECT id, temperature, 5 | LAG(temperature) OVER (ORDER BY recordDate) AS prv_temp, 6 | DATEDIFF(DAY, LAG(recordDate) OVER (ORDER BY recordDate), recordDate) AS day_diff 7 | FROM Weather 8 | ) AS temp_comp 9 | WHERE day_diff = 1 10 | AND temperature > prv_temp; 11 | 12 | 13 | 14 | -- **************** Alternative using aliases for clarity **************** 15 | 16 | -- SELECT id 17 | -- FROM ( 18 | -- SELECT id, 19 | -- temperature, 20 | -- LAG(temperature) OVER (ORDER BY recordDate) AS previous_day_temperature, -- Previous day's temperature 21 | -- DATEDIFF(DAY, LAG(recordDate) OVER (ORDER BY recordDate), recordDate) AS day_difference -- Difference in days between current and previous record dates 22 | -- FROM Weather 23 | -- ) AS temp_comp 24 | -- WHERE day_difference = 1 -- Ensure the previous record is exactly 1 day before the current record 25 | -- AND temperature > previous_day_temperature; -- Compare current day's temperature with the previous day's temperature 26 | 27 | -- **************** My main solution using self join **************** 28 | 29 | -- select cur.id 30 | -- from Weather as cur 31 | -- join Weather as pre 32 | -- on cur.recordDate = DateAdd(day,1,pre.recordDate) 33 | -- where cur.temperature > pre.temperature -------------------------------------------------------------------------------- /1978-Employees-Whose-Manager-Left-the-Company.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT e.employee_id 3 | FROM Employees e 4 | JOIN Employees m 5 | ON m.employee_id = e.employee_id 6 | WHERE e.salary < 30000 7 | AND e.manager_id IS NOT NULL 8 | AND m.manager_id NOT IN (SELECT employee_id FROM Employees) 9 | ORDER BY e.employee_id -------------------------------------------------------------------------------- /2356-Number-of-Unique-Subjects-Taught-by-Each-Teacher.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | SELECT teacher_id ,COUNT(DISTINCT subject_id ) AS cnt 3 | FROM Teacher 4 | GROUP BY teacher_id -------------------------------------------------------------------------------- /550-Game-Play-Analysis-IV.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH JoinDate AS ( 3 | SELECT 4 | player_id, 5 | MIN(event_date) AS join_date 6 | FROM Activity 7 | GROUP BY player_id 8 | ), 9 | AllUser AS ( 10 | SELECT 11 | COUNT(DISTINCT player_id) AS all_user 12 | FROM Activity 13 | ) 14 | SELECT 15 | ROUND( 16 | CAST(SUM(CASE WHEN DATEADD(day, 1, j.join_date) = a.event_date THEN 1 ELSE 0 END) AS FLOAT) 17 | / (SELECT all_user FROM AllUser), 18 | 2 19 | ) AS fraction 20 | FROM Activity a 21 | JOIN JoinDate j ON a.player_id = j.player_id 22 | -------------------------------------------------------------------------------- /570-Managers-with-at-Least-5-Direct-Reports.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | select e1.name 3 | from Employee e1 4 | join Employee e2 5 | ON e1.id =e2.managerId 6 | GROUP BY e1.id, e1.name 7 | HAVING COUNT(e2.id) >= 5; -------------------------------------------------------------------------------- /577-Employee-Bonus.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | select e.name , b.bonus 3 | from Employee e 4 | left join Bonus b on e.empId = b.empId 5 | where b.bonus<1000 or b.bonus is null -------------------------------------------------------------------------------- /584-Find-Customer-Referee.sql: -------------------------------------------------------------------------------- 1 | -- Write your PostgreSQL query statement below 2 | select c.name from customer c 3 | where c.referee_id is NULL or c.referee_id != 2 -------------------------------------------------------------------------------- /585-Investments-in-2016.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH DuplicateTiv AS ( 3 | SELECT tiv_2015 4 | FROM Insurance 5 | GROUP BY tiv_2015 6 | HAVING COUNT(pid) > 1 7 | ), 8 | UniqueLocations AS ( 9 | SELECT lat, lon 10 | FROM Insurance 11 | GROUP BY lat, lon 12 | HAVING COUNT(pid) = 1 13 | ) 14 | SELECT ROUND(SUM(i.tiv_2016), 2) AS tiv_2016 15 | FROM Insurance i 16 | JOIN DuplicateTiv dt ON i.tiv_2015 = dt.tiv_2015 17 | JOIN UniqueLocations ul ON i.lat = ul.lat AND i.lon = ul.lon; 18 | -------------------------------------------------------------------------------- /595-Big-Countries.tsql: -------------------------------------------------------------------------------- 1 | SELECT name, population, area 2 | FROM world 3 | WHERE area >= 3000000 OR population >= 25000000; 4 | -------------------------------------------------------------------------------- /596-Classes-More-Than-5-Students.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | SELECT class 3 | FROM Courses 4 | GROUP BY class 5 | HAVING COUNT(class) >= 5 -------------------------------------------------------------------------------- /602-Friend-Requests-II:-Who-Has-the-Most-Friends.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH FriendCounts AS ( 3 | SELECT requester_id AS user_id 4 | FROM RequestAccepted 5 | UNION ALL 6 | SELECT accepter_id AS user_id 7 | FROM RequestAccepted 8 | ), 9 | UserFriendCounts AS ( 10 | SELECT user_id, COUNT( user_id) AS num_friends 11 | FROM FriendCounts 12 | GROUP BY user_id 13 | ) 14 | SELECT TOP 1 user_id AS id, num_friends AS num 15 | FROM UserFriendCounts 16 | ORDER BY num_friends DESC; 17 | -------------------------------------------------------------------------------- /610-Triangle-Judgement.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | -- TO SAY THAT IS triangle 3 | -- x+y>z 4 | -- x+z>y 5 | -- y+z>x 6 | 7 | SELECT X ,Y ,Z , 8 | CASE WHEN X+Y>Z AND X+Z>Y AND Y+Z>X THEN 'Yes' ELSE 'No' END AS triangle 9 | FROM Triangle -------------------------------------------------------------------------------- /619-Biggest-Single-Number.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | WITH SingleNumbers AS( 3 | SELECT num 4 | FROM MyNumbers 5 | GROUP BY num 6 | HAVING COUNT(num) = 1 7 | ) 8 | SELECT MAX(num) AS num FROM SingleNumbers 9 | 10 | 11 | -------------------------------------------------------------------------------- /620-Not-Boring-Movies.tsql: -------------------------------------------------------------------------------- 1 | /* Write your T-SQL query statement below */ 2 | select * from Cinema 3 | where id % 2 = 1 and description != 'boring' 4 | order by rating desc -------------------------------------------------------------------------------- /626-Exchange-Seats.tsql: -------------------------------------------------------------------------------- 1 | -- first solve 2 | -- SELECT 3 | -- s1.id, 4 | -- CASE 5 | -- WHEN s1.id % 2 = 1 AND s2.student IS NOT NULL THEN s2.student 6 | -- WHEN s1.id % 2 = 0 THEN s2.student 7 | -- ELSE s1.student 8 | -- END AS student 9 | -- FROM Seat s1 10 | -- LEFT JOIN Seat s2 11 | -- ON 12 | -- (s1.id % 2 = 1 AND s1.id = s2.id - 1) 13 | -- OR (s1.id % 2 = 0 AND s1.id = s2.id + 1) 14 | 15 | --------------------------------------------------------------------------------------------------------- 16 | -- second solve 17 | SELECT ROW_NUMBER() OVER(ORDER BY CASE WHEN id % 2 = 0 THEN id-1 ELSE id+1 END) AS id, student FROM Seat 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode SQL 50 With T-SQL 2 | 3 | This repository contains my solutions to LeetCode problems. 4 | 5 | ![Grey Green Modern Minimalist Business Zoom Virtual Background (1)](https://github.com/user-attachments/assets/da95438f-9637-4d90-afc5-d0ecc808fb8a) 6 | 7 | 8 | 9 | # BESSA IS HERE 10 | - GitHub: [mrXrobot26](https://github.com/mrXrobot26) 11 | - LinkedIn: [Bess Gates](https://www.linkedin.com/in/bess-gates/) 12 | - Twitter: [@MrXroboT](https://x.com/MrXroboT) 13 | - YouTube: [Bess_Gates](https://www.youtube.com/@Bess_Gates) 14 | - Facebook: [Abdo Elbessa](https://www.facebook.com/abdo.elbessa10/) 15 | --------------------------------------------------------------------------------