Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions problem1-180-consecutive-numbers.sql
Original file line number Diff line number Diff line change
@@ -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;
25 changes: 25 additions & 0 deletions problem2-2142-number-of-passanger-bus.sql
Original file line number Diff line number Diff line change
@@ -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;
8 changes: 8 additions & 0 deletions problem3-1141-user-activity-30days.sql
Original file line number Diff line number Diff line change
@@ -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
19 changes: 19 additions & 0 deletions problem4-2252-dynemic-pivot-table.sql
Original file line number Diff line number Diff line change
@@ -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