diff --git a/ConsecutiveNumbers.sql b/ConsecutiveNumbers.sql new file mode 100644 index 0000000..e994ad5 --- /dev/null +++ b/ConsecutiveNumbers.sql @@ -0,0 +1,9 @@ +''' +Sql3 + +1 Problem 1 : Consecutive Numbers (https://leetcode.com/problems/consecutive-numbers/) +''' + +SELECT DISTINCT(l1.num) AS ConsecutiveNums +FROM Logs l1, Logs l2, Logs l3 +WHERE (l1.id = l2.id-1) AND (l2.id = l3.id-1) AND (l1.num = l2.num) AND (l2.num = l3.num) \ No newline at end of file diff --git a/DynamicPivotingOfATable.sql b/DynamicPivotingOfATable.sql new file mode 100644 index 0000000..c60351d --- /dev/null +++ b/DynamicPivotingOfATable.sql @@ -0,0 +1,18 @@ +''' +4 Problem 4 :Dynamic Pivoting of a Table ( https://leetcode.com/problems/dynamic-pivoting-of-a-table/ ) +''' + +CREATE PROCEDURE PivotProducts() +BEGIN + # Write your MySQL query statement below. +SET GROUP_CONCAT_MAX_LEN = 1000000; + SELECT GROUP_CONCAT(DISTINCT CONCAT('SUM(IF(store = "', store, '", price, null)) as ' , store)) + INTO @sql FROM products; + + SET @sql = CONCAT('SELECT product_id,', @sql, ' FROM Products GROUP BY 1'); + + PREPARE statement FROM @sql; + EXECUTE statement; + DEALLOCATE PREPARE STATEMENT; + +END \ No newline at end of file diff --git a/NumberOfPassengersInEachBus.sql b/NumberOfPassengersInEachBus.sql new file mode 100644 index 0000000..a13dfd2 --- /dev/null +++ b/NumberOfPassengersInEachBus.sql @@ -0,0 +1,16 @@ +''' +2 Problem 2 :Number of Passengers in Each Bus ( https://leetcode.com/problems/the-number-of-passengers-in-each-bus-i/ ) + +''' + +WITH CTE AS ( + SELECT passenger_id, Passengers.arrival_time, MIN(Buses.arrival_time) AS btime + FROM Passengers + JOIN Buses ON Passengers.arrival_time <= Buses.arrival_time + GROUP BY passenger_id +) +SELECT bus_id, COUNT(btime) AS Passengers_cnt +FROM Buses +LEFT JOIN CTE ON btime = Buses.arrival_time +GROUP BY bus_id +ORDER BY bus_id \ No newline at end of file diff --git a/UserActivity.sql b/UserActivity.sql new file mode 100644 index 0000000..9333378 --- /dev/null +++ b/UserActivity.sql @@ -0,0 +1,8 @@ +''' +3 Problem 3 :User Activity (https://leetcode.com/problems/user-activity-for-the-past-30-days-i/ ) +''' + +SELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users +FROM Activity +WHERE activity_date BETWEEN '2019-06-28' AND '2019-07-27' +GROUP BY day \ No newline at end of file