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
20 changes: 20 additions & 0 deletions Problem 4 Dynamic Pivoting of a Table.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
CREATE PROCEDURE PivotProducts()
BEGIN

SET SESSION GROUP_CONCAT_MAX_LEN = 1000000;
# Step 1: Generate dynamic SQL for pivot columns
SELECT GROUP_CONCAT(DISTINCT CONCAT('SUM(IF(store = "', store, '", price, NULL)) AS `', store, '`')) INTO @sql
FROM products;

# Step 2: Construct the complete dynamic SQL query
SET @sql = CONCAT(
'SELECT product_id, ',
@sql,
' FROM products GROUP BY product_id'
);
# Step 3: Prepare and execute the dynamic SQL
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END
22 changes: 22 additions & 0 deletions Problem1ConsecutiveNumebrs.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Write your MySQL query statement below
-- Step 1: Create a Common Table Expression (CTE) to compare the current row with the next two rows
WITH ConsecutiveNumsCTE AS (
SELECT
l1.id AS CurrentID, -- ID of the current row
l1.num AS CurrentNum, -- Number of the current row
l2.num AS NextNum, -- Number from the next row
l3.num AS SecondNextNum -- Number from the second next row
FROM Logs l1
-- Join the table with itself to get the next row (ID = CurrentID + 1)
LEFT JOIN Logs l2
ON l1.id = l2.id - 1
-- Join the table again to get the second next row (ID = CurrentID + 2)
LEFT JOIN Logs l3
ON l1.id = l3.id - 2
)

-- Step 2: Select numbers that appear three times consecutively
SELECT DISTINCT CurrentNum AS ConsecutiveNums
FROM ConsecutiveNumsCTE
-- Filter rows where the current number is equal to both the next and the second next number
WHERE CurrentNum = NextNum AND NextNum = SecondNextNum;
16 changes: 16 additions & 0 deletions Problem2PassengersinEachBus.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
WITH BusTime AS (
SELECT bus_id, arrival_time, LAG(arrival_time,1,0) OVER (ORDER BY arrival_time) AS previous_arrival_time
FROM Buses
),
FinalArrivalTime AS (
SELECT b.bus_id, p.passenger_id
FROM BusTime b
LEFT JOIN Passengers p
ON p.arrival_time>b.previous_arrival_time AND p.arrival_time<=b.arrival_time
)


SELECT f.bus_id, COUNT(f.passenger_id) AS passengers_cnt
FROM FinalArrivalTime f
GROUP BY f.bus_id
ORDER BY f.bus_id
8 changes: 8 additions & 0 deletions Problem3User Activity.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
WITH CTE AS (
SELECT DISTINCT activity_date as day, user_id FROM Activity
WHERE activity_date BETWEEN DATE_ADD( '2019-07-27' , INTERVAL -29 DAY) AND '2019-07-27'
)

SELECT CTE.day, COUNT(DISTINCT user_id) AS active_users
FROM CTE
GROUP BY CTE.day