Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

completed sql3 #28

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
7 changes: 7 additions & 0 deletions problem_1.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
--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;
12 changes: 12 additions & 0 deletions problem_2.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- Number of Passengers in Each Bus

WITH CTE AS
(SELECT p.passenger_id, p.arrival_time, MIN(b.arrival_time) AS btime
FROM Passengers p
INNER JOIN Buses b ON p.arrival_time <= b.arrival_time
GROUP BY p.passenger_id)

SELECT b.bus_id, COUNT(c.btime) AS passengers_cnt
FROM buses b LEFT JOIN CTE c ON b.arrival_time = c.btime
GROUP BY b.bus_id
ORDER BY b.bus_id;
6 changes: 6 additions & 0 deletions problem_3.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
--User Activity

SELECT activity_date AS 'day',
COUNT(DISTINCT user_id) AS 'active_users'
FROM Activity WHERE activity_date > '2019-06-27' AND activity_date <= '2019-07-27'
GROUP BY activity_date;
23 changes: 23 additions & 0 deletions problem_4.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
--Dynamic Pivoting of a Table

CREATE PROCEDURE PivotProducts()
BEGIN
-- Set the maximum length for GROUP_CONCAT
SET SESSION GROUP_CONCAT_MAX_LEN = 1000000;

-- Generate dynamic SQL for pivoting
SELECT GROUP_CONCAT(
DISTINCT CONCAT('SUM(IF(Store = "', store, '", Price, NULL)) AS ', store)
) INTO @SQL
FROM Products;

-- Construct the final SQL query
SET @SQL = CONCAT(
'SELECT product_id, ', @SQL, ' FROM Products GROUP BY product_id'
);

-- Prepare and execute the SQL statement
PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END