Complex Queries Using CTE & Pivoting
Complex Queries Using CTE & Pivoting
Practice: Get the average days between two consecutive transactions for each
customer.
https://almabetter.notion.site/Complex-queries-using-CTE-Pivoting-1191a19a5617800691b6d8c761500557 1/6
11/24/24, 10:23 PM Complex queries using CTE & Pivoting
Practice: Get the absolute deviation of the transaction amount for each customer
from their average value.
Practice: Keep only details of each customer's first and second transactions.
https://almabetter.notion.site/Complex-queries-using-CTE-Pivoting-1191a19a5617800691b6d8c761500557 2/6
11/24/24, 10:23 PM Complex queries using CTE & Pivoting
CREATE TABLE mining_production ( date DATE NOT NULL, mine_id INT NOT
NULL, mineral VARCHAR(50) NOT NULL, production_quantity INT NOT NULL );
INSERT INTO mining_production (date, mine_id, mineral,
production_quantity) VALUES ('2023-06-01', 1, 'Gold', 150), ('2023-06-
01', 2, 'Silver', 200), ('2023-06-01', 1, 'Copper', 300), ('2023-06-02',
1, 'Gold', 160), ('2023-06-02', 2, 'Silver', 180), ('2023-06-02', 1,
'Copper', 320), ('2023-06-03', 1, 'Gold', 170), ('2023-06-03', 2,
'Silver', 210), ('2023-06-03', 1, 'Copper', 310), ('2023-06-04', 1,
'Gold', 140), ('2023-06-04', 2, 'Silver', 220), ('2023-06-04', 1,
'Copper', 330);
https://almabetter.notion.site/Complex-queries-using-CTE-Pivoting-1191a19a5617800691b6d8c761500557 3/6
11/24/24, 10:23 PM Complex queries using CTE & Pivoting
-- For each mineral, on each day, provide the daily total production, --
the average production of that mineral over all days, -- and indicate
whether the daily production is above or equal to/below -- the average
production. --
-- For each mineral, on each day, provide the daily total production,
SELECT date, mineral, SUM(production_quantity) AS daily_total FROM
mining_production GROUP BY date, mineral
-- the average production of that mineral over all days. SELECT mineral,
AVG(production_quantity) AS avg_production FROM mining_production GROUP
BY mineral -- and indicate whether the daily production is above or equal
to/below -- the average production. --
https://almabetter.notion.site/Complex-queries-using-CTE-Pivoting-1191a19a5617800691b6d8c761500557 4/6
11/24/24, 10:23 PM Complex queries using CTE & Pivoting
Practice: Get the average days between two consecutive transactions for each
customer. (Solve this question using CTE , write subquery as temporary table)
https://almabetter.notion.site/Complex-queries-using-CTE-Pivoting-1191a19a5617800691b6d8c761500557 5/6
11/24/24, 10:23 PM Complex queries using CTE & Pivoting
https://almabetter.notion.site/Complex-queries-using-CTE-Pivoting-1191a19a5617800691b6d8c761500557 6/6