diff --git a/problem1-180-consecutive-numbers.sql b/problem1-180-consecutive-numbers.sql new file mode 100644 index 0000000..4c53d66 --- /dev/null +++ b/problem1-180-consecutive-numbers.sql @@ -0,0 +1,35 @@ +select + distinct log1.num as ConsecutiveNums +from + Logs log1,Logs log2,Logs log3 +where log1.id = log2.id - 1 +and log2.id = log3.id -1 +and log1.num =log2.num +and log2.num =log3.num + + +-- join +SELECT DISTINCT log1.num as ConsecutiveNums +FROM Logs log1 +JOIN Logs log2 ON log1.id = log2.id - 1 +JOIN Logs log3 ON log2.id = log3.id - 1 +WHERE log1.num = log2.num + AND log2.num = log3.num + + +--window function +WITH ThreeConsecutive AS ( + SELECT + CASE + WHEN num = LAG(num, 1) OVER (ORDER BY id) + AND num = LAG(num, 2) OVER (ORDER BY id) + THEN num + END AS ConsecutiveNums + FROM Logs +) + +SELECT + DISTINCT ConsecutiveNums +FROM ThreeConsecutive +WHERE + ConsecutiveNums IS NOT NULL; \ No newline at end of file diff --git a/problem2-2142-number-of-passanger-bus.sql b/problem2-2142-number-of-passanger-bus.sql new file mode 100644 index 0000000..5993247 --- /dev/null +++ b/problem2-2142-number-of-passanger-bus.sql @@ -0,0 +1,25 @@ +WITH bus_time_passenger AS ( + SELECT + p.passenger_id, + MIN(b.arrival_time) AS bus_time + FROM + Passengers p + LEFT JOIN + Buses b + ON p.arrival_time <= b.arrival_time + GROUP BY + p.passenger_id +) + +SELECT + b.bus_id, + COUNT(bp.bus_time) AS passengers_cnt +FROM + Buses b +LEFT JOIN + bus_time_passenger bp + ON bp.bus_time = b.arrival_time +GROUP BY + b.bus_id +ORDER BY + b.bus_id; \ No newline at end of file diff --git a/problem3-1141-user-activity-30days.sql b/problem3-1141-user-activity-30days.sql new file mode 100644 index 0000000..027d9cb --- /dev/null +++ b/problem3-1141-user-activity-30days.sql @@ -0,0 +1,8 @@ +select +activity_date as day, +count(distinct user_id) as active_users +from Activity +where activity_date > DATE_SUB('2019-07-27', INTERVAL 30 DAY) +and activity_date <= '2019-07-27' +group by activity_date +order by activity_date \ No newline at end of file diff --git a/problem4-2252-dynemic-pivot-table.sql b/problem4-2252-dynemic-pivot-table.sql new file mode 100644 index 0000000..81c777d --- /dev/null +++ b/problem4-2252-dynemic-pivot-table.sql @@ -0,0 +1,19 @@ +CREATE PROCEDURE PivotProducts() +BEGIN + + SET SESSION GROUP_CONCAT_MAX_LEN = 10000000; + SET @cols = ( + SELECT + GROUP_CONCAT( DISTINCT + CONCAT('MAX(IF(store = ''',store,''', price, NULL)) AS ', store) + ) + FROM Products order by store); + + SET @query = CONCAT('SELECT product_id, ', @cols, ' FROM Products GROUP BY product_id ;'); + + + PREPARE stmt FROM @query; + EXECUTE stmt; + + +END \ No newline at end of file