diff --git a/02_activities/assignments/DC_Cohort/Assignment1.md b/02_activities/assignments/DC_Cohort/Assignment1.md index f78778f5b..c23f19b5d 100644 --- a/02_activities/assignments/DC_Cohort/Assignment1.md +++ b/02_activities/assignments/DC_Cohort/Assignment1.md @@ -207,3 +207,10 @@ Consider, for example, concepts of fariness, inequality, social structures, marg ``` Your thoughts... ``` +Databases not just as technical tools, but systems reflecting human values. The social implications of how data is organized are familiar from my work in education. This reflection explores how everyday data systems embed assumptions identity, and inclusion. Databases rely on predefined categories, such as gender, family structure, or citizenship. These categories are often taken for granted, but they carry cultural and political weight. + +In my academic environment, student information systems often Western naming conventions. International students or those from nontraditional families may find that their identities don’t fit neatly into the database. Similarly, learning management systems (LMS) track student engagement through metrics like login frequency or discussion posts. These indicators may not account for neurodiverse learners or cultural differences in participation styles, yet they’re used to assess performance. As a researcher, I’ve also encountered limitations in data collection tools. When conducting surveys, I’m often forced to simplify complex identities into checkboxes, race, ethnicity, language, based on institutional templates. These simplifications can erase nuance and reinforce dominant narratives. Ethical research requires acknowledging these constraints and advocating for more inclusive data practices. + +Beyond academia, media platforms like news aggregators and YouTube also reflect embedded value systems. News algorithms often prioritize Western sources, shaping public understanding of global events. Stories from the Global South or Indigenous communities may be underrepresented or framed through Western perspectives. This influences not only what we read, but how we think about the world. YouTube’s recommendation system is another example. It promotes content based on watch time and engagement, which tends to favour popular creators and mainstream topics. Marginalized voices, such as disabled educators, or those speaking in non-dominant languages, struggle for visibility. The algorithm amplifies what’s already dominant, reinforcing cultural hierarchies. + +As an educator, I believe fairness means recognizing diverse ways of knowing and being. Data systems may exclude overlook informal learning or penalize students who don’t conform to standardized metrics, thus fall short of this ideal. These systems shape access to resources, recognition, and opportunity. Marginalization can occur invisibly through design. For example, if a database doesn’t allow for multiple guardians or chosen family structures, some students may be denied access to services. If a grading algorithm penalizes late submissions without accounting for caregiving responsibilities or mental health, it reinforces inequity. \ No newline at end of file diff --git a/02_activities/assignments/DC_Cohort/assignment1.png b/02_activities/assignments/DC_Cohort/assignment1.png new file mode 100644 index 000000000..e2e532909 Binary files /dev/null and b/02_activities/assignments/DC_Cohort/assignment1.png differ diff --git a/02_activities/assignments/DC_Cohort/assignment1.sqbpro b/02_activities/assignments/DC_Cohort/assignment1.sqbpro new file mode 100644 index 000000000..349cdfaf6 --- /dev/null +++ b/02_activities/assignments/DC_Cohort/assignment1.sqbpro @@ -0,0 +1,154 @@ +
/* ASSIGNMENT 1 */ +/* SECTION 2 */ + + +--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 customer_purchases +WHERE product_id = 4 +or product_id = 9; + +/*2. Write a query that returns all customer purchases and a new calculated column 'price' (quantity * cost_to_customer_per_qty), +filtered by customer IDs between 8 and 10 (inclusive) using either: + 1. two conditions using AND + 2. one condition using BETWEEN*/ + +-- option 1 +SELECT * +, quantity * cost_to_customer_per_qty AS price +FROM customer_purchases +WHERE customer_id = 8 AND 9 AND 10; + +-- option 2 +SELECT * +,quantity * cost_to_customer_per_qty AS price +FROM customer_purchases +WHERE customer_id BETWEEN 8 AND 10; + +--CASE +/* 1. Products can be sold by the individual unit or by bulk measures like lbs. or oz. +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 product_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 product_id +, product_name +, CASE WHEN product_qty_type = 'unit' THEN 'unit' +ELSE 'bulk' +END as product_qty_type_condensed +, CASE WHEN product_name like '%Peppers%' or '%peppers%' +THEN '1' +ELSE '0' +END as pepper_flag +FROM product; + +--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_booth_assignments +INNER JOIN vendor +on vendor_booth_assignments.vendor_id = vendor.vendor_id +ORDER by vendor_name, market_date; + +/* SECTION 3 */ + +-- 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 (vendor_id) as num_times_booth_rented +FROM vendor_booth_assignments +GROUP BY vendor_id; + +/* 2. The Farmer’s Market Customer Appreciation Committee wants to give a bumper +sticker to everyone who has ever spent more than $2000 at the market. Write a query that generates a list +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_first_name +, c.customer_last_name +, sum(quantity * cost_to_customer_per_qty) as customer_expenditure + + +FROM customer_purchases as cp +INNER JOIN customer as c +on c.customer_id = cp.customer_id +GROUP by c.customer_id, c.customer_first_name, c.customer_last_name +HAVING sum (cp.quantity*cp.cost_to_customer_per_qty) > 2000 +ORDER by c.customer_last_name, c.customer_first_name; + +--Temp Table +/*1. Insert the original vendor table into a temp.new_vendor and then add a 10th vendor: +Thomass Superfood Store, a Fresh Focused store, owned by Thomas Rosenthal + +HINT: This is two total queries -- first create the table from the original, then insert the new 10th vendor. +When inserting the new vendor, you need to appropriately align the columns to be inserted +(there are five columns to be inserted, I've given you the details, but not the syntax) + +-> To insert the new row use VALUES, specifying the value you want for each column: +VALUES(col1,col2,col3,col4,col5) +*/ + +--CREATE TEMP TABLE new_vendor AS +SELECT * FROM vendor; + +INSERT INTO new_vendor (vendor_id, vendor_name, vendor_type, vendor_owner_first_name, vendor_owner_last_name) +VALUES (10, 'Thomass Superfood Store', 'Fresh Focused', 'Thomas', 'Rosenthal'); + +-- Date +/*1. Get the customer_id, month, and year (in separate columns) of every purchase in the customer_purchases table. + +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', market_date) AS purchase_month, +strftime('%Y', market_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. +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', market_date) = '04' +and strftime('%Y', market_date) = '2022' +GROUP BY customer_id + + + + + + +
diff --git a/02_activities/assignments/DC_Cohort/assignment1.sql b/02_activities/assignments/DC_Cohort/assignment1.sql index c992e3205..21e35b559 100644 --- a/02_activities/assignments/DC_Cohort/assignment1.sql +++ b/02_activities/assignments/DC_Cohort/assignment1.sql @@ -4,70 +4,110 @@ --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 customer_purchases +WHERE product_id = 4 +or product_id = 9; /*2. Write a query that returns all customer purchases and a new calculated column 'price' (quantity * cost_to_customer_per_qty), filtered by customer IDs between 8 and 10 (inclusive) using either: 1. two conditions using AND - 2. one condition using BETWEEN -*/ --- option 1 + 2. one condition using BETWEEN*/ +-- option 1 +SELECT * +, quantity * cost_to_customer_per_qty AS price +FROM customer_purchases +WHERE customer_id = 8 AND 9 AND 10; -- option 2 - - +SELECT * +,quantity * cost_to_customer_per_qty AS price +FROM customer_purchases +WHERE customer_id BETWEEN 8 AND 10; --CASE /* 1. Products can be sold by the individual unit or by bulk measures like lbs. or oz. -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” +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 product_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 product_id +, product_name +, CASE WHEN product_qty_type = 'unit' THEN 'unit' +ELSE 'bulk' +END as product_qty_type_condensed +, CASE WHEN product_name like '%Peppers%' or '%peppers%' +THEN '1' +ELSE '0' +END as pepper_flag +FROM product; --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_booth_assignments +INNER JOIN vendor +on vendor_booth_assignments.vendor_id = vendor.vendor_id +ORDER by vendor_name, market_date; /* SECTION 3 */ -- 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 (vendor_id) as num_times_booth_rented +FROM vendor_booth_assignments +GROUP BY vendor_id; /* 2. The Farmer’s Market Customer Appreciation Committee wants to give a bumper sticker to everyone who has ever spent more than $2000 at the market. Write a query that generates a list 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_first_name +, c.customer_last_name +, sum(quantity * cost_to_customer_per_qty) as customer_expenditure +FROM customer_purchases as cp +INNER JOIN customer as c +on c.customer_id = cp.customer_id +GROUP by c.customer_id, c.customer_first_name, c.customer_last_name +HAVING sum (cp.quantity*cp.cost_to_customer_per_qty) > 2000 +ORDER by c.customer_last_name, c.customer_first_name; --Temp Table -/* 1. Insert the original vendor table into a temp.new_vendor and then add a 10th vendor: +/*1. Insert the original vendor table into a temp.new_vendor and then add a 10th vendor: Thomass Superfood Store, a Fresh Focused store, owned by Thomas Rosenthal HINT: This is two total queries -- first create the table from the original, then insert the new 10th vendor. @@ -77,20 +117,37 @@ 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) */ +DROP Table if exists temp.new_vendor_inventory +CREATE TABLE temp.new_vendor AS +SELECT * FROM vendor; - +INSERT INTO new_vendor (vendor_id, vendor_name, vendor_type, vendor_owner_first_name, vendor_owner_last_name) +VALUES (10, 'Thomass Superfood Store', 'Fresh Focused', 'Thomas', 'Rosenthal'); -- Date /*1. Get the customer_id, month, and year (in separate columns) of every purchase in the customer_purchases table. 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', market_date) AS purchase_month, +strftime('%Y', market_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. 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', market_date) = '04' +and strftime('%Y', market_date) = '2022' +GROUP BY customer_id + + + + + diff --git a/02_activities/assignments/DC_Cohort/assignment1.txt b/02_activities/assignments/DC_Cohort/assignment1.txt new file mode 100644 index 000000000..1b2109502 --- /dev/null +++ b/02_activities/assignments/DC_Cohort/assignment1.txt @@ -0,0 +1,29 @@ +## Section 4: +You can start this section anytime. + +Steps to complete this part of the assignment: +- Read the article +- Write, within this markdown file, <1000 words. + +### Ethics + +Read: Qadri, R. (2021, November 11). _When Databases Get to Define Family._ Wired.
+ https://www.wired.com/story/pakistan-digital-database-family-design/ + +Link if you encounter a paywall: https://archive.is/srKHV or https://web.archive.org/web/20240422105834/https://www.wired.com/story/pakistan-digital-database-family-design/ + +**What values systems are embedded in databases and data systems you encounter in your day-to-day life?** + +Consider, for example, concepts of fariness, inequality, social structures, marginalization, intersection of technology and society, etc. + + +``` +Your thoughts... +``` +Databases not just as technical tools, but systems reflecting human values. The social implications of how data is organized are familiar from my work in education. This reflection explores how everyday data systems embed assumptions identity, and inclusion. Databases rely on predefined categories, such as gender, family structure, or citizenship. These categories are often taken for granted, but they carry cultural and political weight. + +In my academic environment, student information systems often Western naming conventions. International students or those from nontraditional families may find that their identities don’t fit neatly into the database. Similarly, learning management systems (LMS) track student engagement through metrics like login frequency or discussion posts. These indicators may not account for neurodiverse learners or cultural differences in participation styles, yet they’re used to assess performance. As a researcher, I’ve also encountered limitations in data collection tools. When conducting surveys, I’m often forced to simplify complex identities into checkboxes, race, ethnicity, language, based on institutional templates. These simplifications can erase nuance and reinforce dominant narratives. Ethical research requires acknowledging these constraints and advocating for more inclusive data practices. + +Beyond academia, media platforms like news aggregators and YouTube also reflect embedded value systems. News algorithms often prioritize Western sources, shaping public understanding of global events. Stories from the Global South or Indigenous communities may be underrepresented or framed through Western perspectives. This influences not only what we read, but how we think about the world. YouTube’s recommendation system is another example. It promotes content based on watch time and engagement, which tends to favour popular creators and mainstream topics. Marginalized voices, such as disabled educators, or those speaking in non-dominant languages, struggle for visibility. The algorithm amplifies what’s already dominant, reinforcing cultural hierarchies. + +As an educator, I believe fairness means recognizing diverse ways of knowing and being. Data systems may exclude overlook informal learning or penalize students who don’t conform to standardized metrics, thus fall short of this ideal. These systems shape access to resources, recognition, and opportunity. Marginalization can occur invisibly through design. For example, if a database doesn’t allow for multiple guardians or chosen family structures, some students may be denied access to services. If a grading algorithm penalizes late submissions without accounting for caregiving responsibilities or mental health, it reinforces inequity. \ No newline at end of file diff --git a/02_activities/assignments/DC_Cohort/assignment2.png b/02_activities/assignments/DC_Cohort/assignment2.png new file mode 100644 index 000000000..2230ee94e Binary files /dev/null and b/02_activities/assignments/DC_Cohort/assignment2.png differ diff --git a/02_activities/assignments/DC_Cohort/assignment2.sql b/02_activities/assignments/DC_Cohort/assignment2.sql index 5ad40748a..8ec15239d 100644 --- a/02_activities/assignments/DC_Cohort/assignment2.sql +++ b/02_activities/assignments/DC_Cohort/assignment2.sql @@ -5,21 +5,25 @@ /* 1. Our favourite manager wants a detailed long list of products, but is afraid of tables! We tell them, no problem! We can produce a list with all of the appropriate details. -Using the following syntax you create our super cool and not at all needy manager a list: +Using the following syntax you create our super cool and not at all needy manager a list:*/ SELECT product_name || ', ' || product_size|| ' (' || product_qty_type || ')' -FROM product +from product; + -But wait! The product table has some bad data (a few NULL values). -Find the NULLs and then using COALESCE, replace the NULL with a -blank for the first problem, and 'unit' for the second problem. +/*But wait! The product table has some bad data (a few NULL values). +Find the NULLs and then using COALESCE, replace the NULL with a blank for the first column with +nulls, and 'unit' for the second column with nulls. -HINT: keep the syntax the same, but edited the correct components with the string. +**HINT**: keep the syntax the same, but edited the correct components with the string. 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.) */ +All the other rows will remain the same. */ +SELECT +coalesce(product_name,'') || ', ' || product_size || ' (' || coalesce(product_qty_type, 'unit') || ')' +FROM product; --Windowed Functions @@ -31,6 +35,11 @@ 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(). */ +SELECT +customer_id, +market_date, +ROW_NUMBER() OVER (partition by customer_id ORDER BY market_date) as visit_number +FROM customer_purchases; @@ -38,10 +47,25 @@ HINT: One of these approaches uses ROW_NUMBER() and one uses DENSE_RANK(). */ 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. */ +SELECT * +FROM( +SELECT +customer_id, +market_date, +ROW_NUMBER() OVER (Partition by customer_id order by market_date DESC) AS visit_number +FROM customer_purchases +) AS numbered_visits +WHERE visit_number = 1; /* 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, +product_id, +market_date, +COUNT(*) OVER (PARTITION BY customer_id, product_id) AS times_purchased +FROM customer_purchases; @@ -57,10 +81,17 @@ 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, +Trim(SUBSTR(product_name,Instr(product_name, '-') + 1)) AS description +FROM product; /* 2. Filter the query to show any product_size value that contain a number with REGEXP. */ - +SELECT + product_name, + product_size +FROM product +WHERE product_size REGEXP '[0-9]'; -- UNION @@ -73,6 +104,32 @@ HINT: There are a possibly a few ways to do this query, but if you're struggling 3) Query the second temp table twice, once for the best day, once for the worst day, with a UNION binding them. */ +WITH sales_by_date AS +( +SELECT +market_date, +SUM(cost_to_customer_per_qty * quantity) AS total_sales +FROM customer_purchases +GROUP BY market_date +), +ranked_sales AS +( +SELECT +market_date, +total_sales, +RANK() OVER (ORDER BY total_sales DESC) AS best_rank, +RANK() OVER (ORDER BY total_sales ASC) AS worst_rank +FROM sales_by_date +) +SELECT market_date, total_sales, 'Best Day' AS best_or_worst +FROM ranked_sales +WHERE best_rank = 1 + +UNION + +SELECT market_date, total_sales, 'Worst Day' AS best_or_worst +FROM ranked_sales +WHERE worst_rank = 1; @@ -89,7 +146,24 @@ 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 +v.vendor_name, +p.product_name, +vi.original_price * 5 * COUNT(c.customer_id) AS total_revenue +FROM +vendor AS v +INNER JOIN +vendor_inventory AS vi ON v.vendor_id = vi.vendor_id +INNER JOIN +product AS p ON vi.product_id = p.product_id +CROSS JOIN +customer AS c +GROUP BY +v.vendor_name, +p.product_name, +vi.original_price +ORDER BY +total_revenue DESC; -- INSERT /*1. Create a new table "product_units". @@ -97,11 +171,18 @@ 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). */ +INSERT INTO product_units +VALUES (24,'Apple Pie','large',17,'unit', CURRENT_TIMESTAMP); -- DELETE @@ -109,16 +190,18 @@ 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_id = 24 -- 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. +First, add a new column, current_quantity to the table using the following syntax.*/ ALTER TABLE product_units ADD current_quantity INT; -Then, using UPDATE, change the current_quantity equal to the last quantity value from the vendor_inventory details. +/* 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. @@ -128,6 +211,17 @@ 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 as pu +SET current_quantity = +( +SELECT COALESCE(vi.quantity, 0) +FROM vendor_inventory as vi +WHERE vi.product_id = pu.product_id +ORDER BY vi.market_date DESC +LIMIT 1 +) +WHERE pu.product_id IN ( +SELECT DISTINCT product_id +FROM vendor_inventory +); diff --git a/02_activities/assignments/DC_Cohort/assignment2.txt b/02_activities/assignments/DC_Cohort/assignment2.txt new file mode 100644 index 000000000..8ec15239d --- /dev/null +++ b/02_activities/assignments/DC_Cohort/assignment2.txt @@ -0,0 +1,227 @@ +/* ASSIGNMENT 2 */ +/* SECTION 2 */ + +-- COALESCE +/* 1. Our favourite manager wants a detailed long list of products, but is afraid of tables! +We tell them, no problem! We can produce a list with all of the appropriate details. + +Using the following syntax you create our super cool and not at all needy manager a list:*/ + +SELECT +product_name || ', ' || product_size|| ' (' || product_qty_type || ')' +from product; + + +/*But wait! The product table has some bad data (a few NULL values). +Find the NULLs and then using COALESCE, replace the NULL with a blank for the first column with +nulls, and 'unit' for the second column with nulls. + +**HINT**: keep the syntax the same, but edited the correct components with the string. +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 +coalesce(product_name,'') || ', ' || product_size || ' (' || coalesce(product_qty_type, 'unit') || ')' +FROM product; + + +--Windowed Functions +/* 1. Write a query that selects from the customer_purchases table and numbers each customer’s +visits to the farmer’s market (labeling each market date with a different number). +Each customer’s first visit is labeled 1, second visit is labeled 2, etc. + +You can either display all rows in the customer_purchases table, with the counter changing on +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(). */ +SELECT +customer_id, +market_date, +ROW_NUMBER() OVER (partition by customer_id ORDER BY market_date) as visit_number +FROM customer_purchases; + + + +/* 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. */ + +SELECT * +FROM( +SELECT +customer_id, +market_date, +ROW_NUMBER() OVER (Partition by customer_id order by market_date DESC) AS visit_number +FROM customer_purchases +) AS numbered_visits +WHERE visit_number = 1; + + +/* 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, +product_id, +market_date, +COUNT(*) OVER (PARTITION BY customer_id, product_id) AS times_purchased +FROM customer_purchases; + + + +-- String manipulations +/* 1. Some product names in the product table have descriptions like "Jar" or "Organic". +These are separated from the product name with a hyphen. +Create a column using SUBSTR (and a couple of other commands) that captures these, but is otherwise NULL. +Remove any trailing or leading whitespaces. Don't just use a case statement for each product! + +| product_name | description | +|----------------------------|-------------| +| Habanero Peppers - Organic | Organic | + +Hint: you might need to use INSTR(product_name,'-') to find the hyphens. INSTR will help split the column. */ + +SELECT +product_name, +Trim(SUBSTR(product_name,Instr(product_name, '-') + 1)) AS description +FROM product; + +/* 2. Filter the query to show any product_size value that contain a number with REGEXP. */ +SELECT + product_name, + product_size +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; +2) Create another CTE/Temp table with a rank windowed function on the previous query to create +"best day" and "worst day"; +3) Query the second temp table twice, once for the best day, once for the worst day, +with a UNION binding them. */ + +WITH sales_by_date AS +( +SELECT +market_date, +SUM(cost_to_customer_per_qty * quantity) AS total_sales +FROM customer_purchases +GROUP BY market_date +), +ranked_sales AS +( +SELECT +market_date, +total_sales, +RANK() OVER (ORDER BY total_sales DESC) AS best_rank, +RANK() OVER (ORDER BY total_sales ASC) AS worst_rank +FROM sales_by_date +) +SELECT market_date, total_sales, 'Best Day' AS best_or_worst +FROM ranked_sales +WHERE best_rank = 1 + +UNION + +SELECT market_date, total_sales, 'Worst Day' AS best_or_worst +FROM ranked_sales +WHERE worst_rank = 1; + + + +/* SECTION 3 */ + +-- Cross Join +/*1. Suppose every vendor in the `vendor_inventory` table had 5 of each of their products to sell to **every** +customer on record. How much money would each vendor make per product? +Show this by vendor_name and product name, rather than using the IDs. + +HINT: Be sure you select only relevant columns and rows. +Remember, CROSS JOIN will explode your table rows, so CROSS JOIN should likely be a subquery. +Think a bit about the row counts: how many distinct vendors, product names are there (x)? +How many customers are there (y). +Before your final group by you should have the product of those two queries (x*y). */ + +SELECT +v.vendor_name, +p.product_name, +vi.original_price * 5 * COUNT(c.customer_id) AS total_revenue +FROM +vendor AS v +INNER JOIN +vendor_inventory AS vi ON v.vendor_id = vi.vendor_id +INNER JOIN +product AS p ON vi.product_id = p.product_id +CROSS JOIN +customer AS c +GROUP BY +v.vendor_name, +p.product_name, +vi.original_price +ORDER BY +total_revenue DESC; + +-- INSERT +/*1. Create a new table "product_units". +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). */ + +INSERT INTO product_units +VALUES (24,'Apple Pie','large',17,'unit', CURRENT_TIMESTAMP); + + +-- DELETE +/* 1. Delete the older record for the whatever product you added. + +HINT: If you don't specify a WHERE clause, you are going to have a bad time.*/ + +DELETE from product_units +WHERE product_id = 24 + + +-- 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; + +/* 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. +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 as pu +SET current_quantity = +( +SELECT COALESCE(vi.quantity, 0) +FROM vendor_inventory as vi +WHERE vi.product_id = pu.product_id +ORDER BY vi.market_date DESC +LIMIT 1 +) +WHERE pu.product_id IN ( +SELECT DISTINCT product_id +FROM vendor_inventory +); +