diff --git a/02_activities/assignments/Cohort_8/Assignment2_Tables.pdf b/02_activities/assignments/Cohort_8/Assignment2_Tables.pdf new file mode 100644 index 000000000..9b9b906a3 Binary files /dev/null and b/02_activities/assignments/Cohort_8/Assignment2_Tables.pdf differ diff --git a/02_activities/assignments/Cohort_8/assignment1/Farmers market logical model.drawio.png b/02_activities/assignments/Cohort_8/assignment1/Farmers market logical model.drawio.png new file mode 100644 index 000000000..7f9cf7408 Binary files /dev/null and b/02_activities/assignments/Cohort_8/assignment1/Farmers market logical model.drawio.png differ diff --git a/02_activities/assignments/Cohort_8/assignment1.sql b/02_activities/assignments/Cohort_8/assignment1/assignment1.sql similarity index 60% rename from 02_activities/assignments/Cohort_8/assignment1.sql rename to 02_activities/assignments/Cohort_8/assignment1/assignment1.sql index c992e3205..4857e0d8a 100644 --- a/02_activities/assignments/Cohort_8/assignment1.sql +++ b/02_activities/assignments/Cohort_8/assignment1/assignment1.sql @@ -4,17 +4,22 @@ --SELECT /* 1. Write a query that returns everything in the customer table. */ - +SELECT * FROM customer; /* 2. Write a query that displays all of the columns and 10 rows from the cus- tomer table, sorted by customer_last_name, then customer_first_ name. */ - +SELECT * +FROM customer +ORDER BY customer_last_name, customer_first_name +LIMIT 10; --WHERE /* 1. Write a query that returns all customer purchases of product IDs 4 and 9. */ - +SELECT * +FROM purchases +WHERE product_id IN (4, 9); /*2. Write a query that returns all customer purchases and a new calculated column 'price' (quantity * cost_to_customer_per_qty), @@ -23,10 +28,17 @@ filtered by customer IDs between 8 and 10 (inclusive) using either: 2. one condition using BETWEEN */ -- option 1 - + SELECT *, + (quantity * cost_to_customer_per_qty) AS price +FROM customer_purchases +WHERE customer_id >= 8 + AND customer_id <= 10; -- option 2 - +SELECT *, + (quantity * cost_to_customer_per_qty) AS price +FROM customer_purchases +WHERE customer_id BETWEEN 8 AND 10; --CASE @@ -34,19 +46,37 @@ filtered by customer IDs between 8 and 10 (inclusive) using either: Using the product table, write a query that outputs the product_id and product_name columns and add a column called prod_qty_type_condensed that displays the word “unit” if the product_qty_type is “unit,” and otherwise displays the word “bulk.” */ - +SELECT + product_id, + product_name, + CASE + WHEN product_qty_type = 'unit' THEN 'unit' + ELSE 'bulk' + END AS prod_qty_type_condensed +FROM product; /* 2. We want to flag all of the different types of pepper products that are sold at the market. add a column to the previous query called pepper_flag that outputs a 1 if the product_name contains the word “pepper” (regardless of capitalization), and otherwise outputs 0. */ - +SELECT *, + (quantity * cost_to_customer_per_qty) AS price, + CASE + WHEN LOWER(product_name) LIKE '%pepper%' THEN 1 + ELSE 0 + END AS pepper_flag +FROM customer_purchases +WHERE customer_id BETWEEN 8 AND 10; --JOIN /* 1. Write a query that INNER JOINs the vendor table to the vendor_booth_assignments table on the vendor_id field they both have in common, and sorts the result by vendor_name, then market_date. */ - +SELECT * +FROM vendor v +INNER JOIN vendor_booth_assignments vba + ON v.vendor_id = vba.vendor_id +ORDER BY v.vendor_name, vba.market_date; @@ -55,7 +85,11 @@ vendor_id field they both have in common, and sorts the result by vendor_name, t -- AGGREGATE /* 1. Write a query that determines how many times each vendor has rented a booth at the farmer’s market by counting the vendor booth assignments per vendor_id. */ - +SELECT + vendor_id, + COUNT(*) AS booth_rental_count +FROM vendor_booth_assignments +GROUP BY vendor_id; /* 2. The Farmer’s Market Customer Appreciation Committee wants to give a bumper @@ -63,7 +97,22 @@ sticker to everyone who has ever spent more than $2000 at the market. Write a qu of customers for them to give stickers to, sorted by last name, then first name. HINT: This query requires you to join two tables, use an aggregate function, and use the HAVING keyword. */ - +SELECT + c.customer_id, + c.customer_last_name, + c.customer_first_name, + SUM(p.quantity * p.cost_to_customer_per_qty) AS total_spent +FROM customer c +JOIN customer_purchases p + ON c.customer_id = p.customer_id +GROUP BY + c.customer_id, + c.customer_last_name, + c.customer_first_name +HAVING SUM(p.quantity * p.cost_to_customer_per_qty) > 2000 +ORDER BY + c.customer_last_name, + c.customer_first_name; --Temp Table @@ -77,7 +126,12 @@ When inserting the new vendor, you need to appropriately align the columns to be -> To insert the new row use VALUES, specifying the value you want for each column: VALUES(col1,col2,col3,col4,col5) */ +CREATE TEMP TABLE temp.new_vendor AS +SELECT * +FROM vendor; +INSERT INTO temp.new_vendor (vendor_id, vendor_name, vendor_type, vendor_description) +VALUES (10, 'Thomass Superfood Store', 'Fresh Focused', 'Owner: Thomas Rosenthal'); -- Date @@ -85,7 +139,11 @@ VALUES(col1,col2,col3,col4,col5) HINT: you might need to search for strfrtime modifers sqlite on the web to know what the modifers for month and year are! */ - +SELECT + customer_id, + STRFTIME('%m', purchase_date) AS purchase_month, + STRFTIME('%Y', purchase_date) AS purchase_year +FROM customer_purchases; /* 2. Using the previous query as a base, determine how much money each customer spent in April 2022. @@ -93,4 +151,10 @@ Remember that money spent is quantity*cost_to_customer_per_qty. HINTS: you will need to AGGREGATE, GROUP BY, and filter... but remember, STRFTIME returns a STRING for your WHERE statement!! */ - +SELECT + customer_id, + SUM(quantity * cost_to_customer_per_qty) AS total_spent +FROM customer_purchases +WHERE STRFTIME('%m', purchase_date) = '04' + AND STRFTIME('%Y', purchase_date) = '2022' +GROUP BY customer_id; diff --git a/02_activities/assignments/Cohort_8/assignment2.sql b/02_activities/assignments/Cohort_8/assignment2/assignment2.sql similarity index 53% rename from 02_activities/assignments/Cohort_8/assignment2.sql rename to 02_activities/assignments/Cohort_8/assignment2/assignment2.sql index c2743d3b7..a9e4247d6 100644 --- a/02_activities/assignments/Cohort_8/assignment2.sql +++ b/02_activities/assignments/Cohort_8/assignment2/assignment2.sql @@ -21,7 +21,17 @@ The `||` values concatenate the columns into strings. Edit the appropriate columns -- you're making two edits -- and the NULL rows will be fixed. All the other rows will remain the same. */ +SELECT * +FROM product +WHERE product_name IS NULL + OR product_size IS NULL + OR product_qty_type IS NULL; +SELECT + product_name || ', ' || + COALESCE(product_size, '') || ' (' || + COALESCE(product_qty_type, 'unit') || ')' +FROM product; --Windowed Functions @@ -33,18 +43,66 @@ You can either display all rows in the customer_purchases table, with the counte each new market date for each customer, or select only the unique market dates per customer (without purchase details) and number those visits. HINT: One of these approaches uses ROW_NUMBER() and one uses DENSE_RANK(). */ - - - -/* 2. Reverse the numbering of the query from a part so each customer’s most recent visit is labeled 1, -then write another query that uses this one as a subquery (or temp table) and filters the results to -only the customer’s most recent visit. */ - - - -/* 3. Using a COUNT() window function, include a value along with each row of the -customer_purchases table that indicates how many different times that customer has purchased that product_id. */ - +SELECT + customer_id, + purchase_date, + ROW_NUMBER() OVER ( + PARTITION BY customer_id + ORDER BY purchase_date + ) AS visit_number +FROM customer_purchases; + +SELECT + customer_id, + purchase_date, + DENSE_RANK() OVER ( + PARTITION BY customer_id + ORDER BY purchase_date + ) AS visit_number +FROM ( + SELECT DISTINCT customer_id, purchase_date + FROM customer_purchases + + +SELECT + customer_id, + purchase_date, + DENSE_RANK() OVER ( + PARTITION BY customer_id + ORDER BY purchase_date DESC + ) AS reverse_visit_number +FROM ( + SELECT DISTINCT customer_id, purchase_date + FROM customer_purchases + ); + +SELECT * +FROM ( + SELECT + customer_id, + purchase_date, + DENSE_RANK() OVER ( + PARTITION BY customer_id + ORDER BY purchase_date DESC + ) AS reverse_visit_number + FROM ( + SELECT DISTINCT customer_id, purchase_date + FROM customer_purchases + ) +) +WHERE reverse_visit_number = 1; + + +SELECT + customer_id, + product_id, + purchase_date, + quantity, + cost_to_customer_per_qty, + COUNT(*) OVER ( + PARTITION BY customer_id, product_id + ) AS purchase_count +FROM customer_purchases; -- String manipulations @@ -59,21 +117,60 @@ Remove any trailing or leading whitespaces. Don't just use a case statement for Hint: you might need to use INSTR(product_name,'-') to find the hyphens. INSTR will help split the column. */ - +SELECT + product_name, + -- Extract substring after the hyphen + TRIM( + CASE + WHEN INSTR(product_name, '-') > 0 THEN + SUBSTR(product_name, INSTR(product_name, '-') + 1) + ELSE NULL + END + ) AS description +FROM product; /* 2. Filter the query to show any product_size value that contain a number with REGEXP. */ - +SELECT * +FROM product +WHERE product_size REGEXP '[0-9]'; -- UNION /* 1. Using a UNION, write a query that displays the market dates with the highest and lowest total sales. HINT: There are a possibly a few ways to do this query, but if you're struggling, try the following: -1) Create a CTE/Temp Table to find sales values grouped dates; +1) Create a CTE/Temp Table to find sales values grouped dates; + +WITH sales_per_date AS ( + SELECT + purchase_date AS market_date, + SUM(quantity * cost_to_customer_per_qty) AS total_sales + FROM customer_purchases + GROUP BY purchase_date +) + 2) Create another CTE/Temp table with a rank windowed function on the previous query to create "best day" and "worst day"; +, ranked_sales AS ( + SELECT + market_date, + total_sales, + RANK() OVER (ORDER BY total_sales DESC) AS rank_desc, + RANK() OVER (ORDER BY total_sales ASC) AS rank_asc + FROM sales_per_date +) + 3) Query the second temp table twice, once for the best day, once for the worst day, with a UNION binding them. */ +SELECT market_date, total_sales, 'Best Day' AS label +FROM ranked_sales +WHERE rank_desc = 1 + +UNION + +SELECT market_date, total_sales, 'Worst Day' AS label +FROM ranked_sales +WHERE rank_asc = 1; @@ -91,7 +188,14 @@ Think a bit about the row counts: how many distinct vendors, product names are t How many customers are there (y). Before your final group by you should have the product of those two queries (x*y). */ - +SELECT + vi.vendor_name, + vi.product_name, + SUM(5 * vi.cost_to_customer_per_qty) AS total_potential_revenue +FROM vendor_inventory vi +CROSS JOIN customer c +GROUP BY vi.vendor_name, vi.product_name +ORDER BY vi.vendor_name, vi.product_name; -- INSERT /*1. Create a new table "product_units". @@ -99,10 +203,22 @@ This table will contain only products where the `product_qty_type = 'unit'`. It should use all of the columns from the product table, as well as a new column for the `CURRENT_TIMESTAMP`. Name the timestamp column `snapshot_timestamp`. */ +CREATE TABLE product_units AS +SELECT + *, + CURRENT_TIMESTAMP AS snapshot_timestamp +FROM product +WHERE product_qty_type = 'unit'; /*2. Using `INSERT`, add a new row to the product_units table (with an updated timestamp). This can be any product you desire (e.g. add another record for Apple Pie). */ +PRAGMA table_info('product_units'); + +INSERT INTO product_units + (product_id, product_name, product_size, product_qty_type, cost_to_customer_per_qty, snapshot_timestamp) +VALUES + (101, 'Apple Pie', '1 unit', 'unit', 12.99, CURRENT_TIMESTAMP); @@ -111,25 +227,59 @@ This can be any product you desire (e.g. add another record for Apple Pie). */ HINT: If you don't specify a WHERE clause, you are going to have a bad time.*/ - +DELETE FROM product_units +WHERE product_name = 'Apple Pie' + AND snapshot_timestamp < ( + SELECT MAX(snapshot_timestamp) + FROM product_units + WHERE product_name = 'Apple Pie' + ); -- UPDATE /* 1.We want to add the current_quantity to the product_units table. First, add a new column, current_quantity to the table using the following syntax. ALTER TABLE product_units -ADD current_quantity INT; +ADD COLUMN current_quantity INT; + Then, using UPDATE, change the current_quantity equal to the last quantity value from the vendor_inventory details. HINT: This one is pretty hard. -First, determine how to get the "last" quantity per product. +First, determine how to get the "last" quantity per product. + +SELECT vi.product_id, + COALESCE(vi.quantity, 0) AS last_quantity +FROM vendor_inventory vi +JOIN ( + SELECT product_id, MAX(inventory_timestamp) AS max_ts + FROM vendor_inventory + GROUP BY product_id +) latest +ON vi.product_id = latest.product_id +AND vi.inventory_timestamp = latest.max_ts; + + Second, coalesce null values to 0 (if you don't have null values, figure out how to rearrange your query so you do.) Third, SET current_quantity = (...your select statement...), remembering that WHERE can only accommodate one column. Finally, make sure you have a WHERE statement to update the right row, you'll need to use product_units.product_id to refer to the correct row within the product_units table. When you have all of these components, you can run the update statement. */ +UPDATE product_units +SET current_quantity = ( + SELECT COALESCE(vi.quantity, 0) + FROM vendor_inventory vi + JOIN ( + SELECT product_id, MAX(inventory_timestamp) AS max_ts + FROM vendor_inventory + GROUP BY product_id + ) latest + ON vi.product_id = latest.product_id + AND vi.inventory_timestamp = latest.max_ts + WHERE vi.product_id = product_units.product_id +) +WHERE product_id IN (SELECT product_id FROM vendor_inventory); diff --git a/02_activities/assignments/Cohort_8/sql b/02_activities/assignments/Cohort_8/sql new file mode 160000 index 000000000..326193047 --- /dev/null +++ b/02_activities/assignments/Cohort_8/sql @@ -0,0 +1 @@ +Subproject commit 3261930471465acb3949a6cac82bdf6bf15e8c72