diff --git a/02_activities/Assignment1_Sandbox.sql b/02_activities/Assignment1_Sandbox.sql new file mode 100644 index 000000000..328652bae --- /dev/null +++ b/02_activities/Assignment1_Sandbox.sql @@ -0,0 +1,244 @@ +/* One-to-Many: where a given row within a table can be referenced by multiple rows in +another table */ + +/* Check number of booth numbers available */ +SELECT booth_number +FROM booth -- 12 booth numbers available + +/* Compare how many booth_numbers are in the vendor_booth_assignments, one select with distinct, one without. */ +SELECT booth_number +FROM vendor_booth_assignments -- 921 rows; There are 921 booth_number rows in vendor_booth_assignments. + +SELECT DISTINCT booth_number +FROM vendor_booth_assignments -- 7 rows; There are 7 unique booth numbers assigned to vendor booths. + +/* Compare how many booth_numbers and vendor_id are in vendor_booth_assignments, one select with distinct, one without. */ +SELECT booth_number, vendor_id +FROM vendor_booth_assignments -- 921 rows. There are 921 booth_number and vendor_id rows. + +SELECT DISTINCT booth_number, vendor_id +FROM vendor_booth_assignments -- 11 rows. + +/* Compare how many booth_numbers, vendor_id and market_date are in vendor_booth_assignments, one select with distinct, one without. */ +SELECT booth_number, vendor_id, market_date +FROM vendor_booth_assignments -- 921 rows + +SELECT DISTINCT booth_number, vendor_id, market_date +FROM vendor_booth_assignments -- 921 rows + + +/* Assignment 1 - Section 2 */ + +/* Write a query that returns everything in the customer table. */ + +SELECT customer_id, customer_first_name, customer_last_name, customer_postal_code +FROM customer + +SELECT * +FROM customer + +/* Write a query that displays all of the columns and 10 rows from the customer table, sorted by customer_last_name, then customer_first_ name. */ +SELECT customer_id, customer_first_name, customer_last_name, customer_postal_code +FROM customer +ORDER BY customer_last_name, customer_first_name +LIMIT 10; + +/* 1. Write a query that returns all customer purchases of product IDs 4 and 9. */ +SELECT * +FROM customer_purchases +WHERE product_id = 4 + +SELECT * +FROM customer_purchases +WHERE product_id = 9 + +SELECT * +FROM customer_purchases +WHERE product_id IN (4,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 */ + +SELECT product_id, vendor_id, market_date, customer_id, quantity, cost_to_customer_per_qty, transaction_time, (quantity*cost_to_customer_per_qty) AS price +FROM customer_purchases +WHERE customer_id BETWEEN 8 AND 10 + +/* CASE - Q1 */ +SELECT product_id, product_name +, CASE WHEN product_qty_type = 'unit' + THEN 'unit' + ELSE 'bulk' +END prod_qty_type_condensed +FROM product; + +/* CASE - Q2 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 prod_qty_type_condensed +, CASE WHEN product_name LIKE '%pepper%' + THEN 1 + ELSE 0 + END AS pepper_flag +FROM product; + +/* Section 2 - JOIN 1. Write a query that `INNER JOIN`s 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 +v.vendor_id, +vendor_name, +vendor_type, +vendor_owner_first_name, +vendor_owner_last_name, +booth_number, +market_date +FROM vendor AS v +INNER JOIN vendor_booth_assignments AS vb + ON v.vendor_id = vb.vendor_id + ORDER BY vendor_name, market_date + + +SELECT +v.vendor_id, +vendor_name, +vendor_type, +vendor_owner_first_name, +vendor_owner_last_name, +booth_number, +market_date +FROM vendor_booth_assignments AS vb +INNER JOIN vendor as v + ON v.vendor_id = vb.vendor_id + ORDER BY vendor_name, market_date + +/* Secton 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 +COUNT(booth_number) +, vendor_id +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 +cp.customer_id +,product_id +,quantity +,cost_to_customer_per_qty +,customer_last_name +,customer_first_name +,market_date +,transaction_time +,SUM(quantity*cost_to_customer_per_qty) AS purchase_total + +FROM customer_purchases AS cp +LEFT JOIN customer AS c + ON cp.customer_id = c.customer_id +ORDER BY customer_last_name, customer_first_name, customer_id +GROUP BY cp.customer_id + +HAVING purchase_total > 2000 + + +SELECT +cp.customer_id +--,product_id +--,quantity +--,cost_to_customer_per_qty +,customer_last_name +,customer_first_name +--,market_date +--,transaction_time +,SUM(quantity*cost_to_customer_per_qty) AS purchase_total +FROM customer_purchases AS cp +LEFT JOIN customer AS c + ON cp.customer_id = c.customer_id +GROUP BY cp.customer_id +HAVING purchase_total > 2000 +ORDER BY customer_last_name, customer_first_name + +, cp.customer_id + +/* 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)` +*/ + +-- if a table named new_vendor exists, delete it, other do NOTHING +DROP TABLE IF EXISTS temp.new_vendor + +--make the temporary new_vendor table +CREATE TABLE temp.new_vendor AS + +-- define the table +SELECT * +FROM vendor; + +-- put the temp.new_vendor into temp.new_new_vendor + +-- if a table named new_new_vendor exists, delete it, other do NOTHING +DROP TABLE IF EXISTS temp.new_new_vendor; + +-- make the temporary new_new_vendor table +CREATE TABLE temp.new_new_vendor AS + +SELECT * +FROM temp.new_vendor; + +-- add a single row of additonal data (see: https://www.w3schools.com/sql/sql_insert.asp) +INSERT INTO temp.new_new_vendor +VALUES (10,'Thomass Superfood Store','Fresh Focused','Thomas','Rosenthal'); + + + +(vendor_id, vendor_name, vendor_type, vendor_owner_first_name, vendor_owner_last_name) +/* 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! + +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!! +*/ + + + + + + + + + + +-- Number of unique vendor_id values +SELECT COUNT(DISTINCT vendor_id) +FROM vendor_booth_assignments + +-- Number of rows with unique combinations of vendor_id and booth_number +SELECT COUNT(*) +From ( + SELECT DISTINCT vendor_id, booth_number + FROM vendor_booth_assignments +) AS number_vendor_booths + +-- Sum of rows with unique combinations of vendor_id and booth_number +SELECT COUNT(*) FROM vendor_booth_assignments + + + + +FROM ( + SELECT DISTINCT vendor_id +vendor_booth_assignments \ No newline at end of file diff --git a/02_activities/assignments/DC_Cohort/Assignment1.md b/02_activities/assignments/DC_Cohort/Assignment1.md index f78778f5b..1887f4dd7 100644 --- a/02_activities/assignments/DC_Cohort/Assignment1.md +++ b/02_activities/assignments/DC_Cohort/Assignment1.md @@ -206,4 +206,6 @@ Consider, for example, concepts of fariness, inequality, social structures, marg ``` Your thoughts... + +When I consider a database that I have spent some time exploring, and the value systems embedded in it, I think of the Ontario Ministry of Education's datasets stored in the Government of Ontario's Data Catalogue: https://data.ontario.ca/dataset/?keywords_en=Education+and+Training. In the two datasets that I've recently downloaded and linked on the variable "district school board" the following: 1. School board financial reports, https://data.ontario.ca/dataset/school-board-financial-reports-estimates-revised-estimates-and-financial-statements, and 2. School information and student demographics https://data.ontario.ca/dataset/school-information-and-student-demographics, political, economic, and social value systems are evident. My interest in the datasets is primarily centred on special education identification and resourcing for students with special education needs. Data variable definitions can be vague and student special education counts vary across school boards, in part because board policies depend not only on the provincial legal framework government policy, but also on local political, economic and community pressures,. This can have the effect of marginalizing some student learning needs and can reinforce inequality of learning opportunity across Ontario's public education system. Moreover, data information definitions do not necessarily track changes in how special education programs are actually administered, generating, in the case of Ontario, essentially a bifurcation in how special education need is measured between "formally" and "informally" identified students and the corresponding funding they receive. Here, the Ontario education data system fails to capture the dynamic nature of public education policy development across the province, over time. ``` diff --git a/02_activities/assignments/DC_Cohort/Assignment2.md b/02_activities/assignments/DC_Cohort/Assignment2.md index 9b804e9ee..e20fdd47e 100644 --- a/02_activities/assignments/DC_Cohort/Assignment2.md +++ b/02_activities/assignments/DC_Cohort/Assignment2.md @@ -54,7 +54,9 @@ The store wants to keep customer addresses. Propose two architectures for the CU **HINT:** search type 1 vs type 2 slowly changing dimensions. ``` -Your answer... +Customers can move, sometimes necessitating address record changes over time. Therefore, it is necessary to decide whether to overwrite the address record with the new data information (Type 1 SCD) or to preserve the former address(es) and update the existing record with the new data information. (Type 2 SCD). It is necessary to add a column to record the date the record was initialized or updated (i.e,., customer_entry_date) and the date the record became obsolete (I.e., customer_end_date). A TRUE/FALSE boolean indicator shows whether the record is a current bookstore customer (TRUE) or former bookstore customer(FALSE). For Type 2 SCD, each update generates an additional customer address record. +Reference: https://www.sqlshack.com/implementing-slowly-changing-dimensions-scds-in-data-warehouses/ + ``` *** @@ -183,5 +185,5 @@ Consider, for example, concepts of labour, bias, LLM proliferation, moderating c ``` -Your thoughts... +A primary ethical issue identified in this story is that the data sets used to train machine learning are subjective entities created and assembled by a collection of individuals.: data sets are no more objective than the human reasoning and motives used to inform them. And that's the crux. Machine learning modelling relies on human input, reflecting an incomplete and flawed understanding of what is presented as an objective and accurate depiction of what is being modelled. Complexity abounds and increases at the intersection of technology and society, especially as people construct more complex models across domains, whether visual representations of physical items or linguistic categorizations of human communication. As complexity increases and people compete to improve the datasets used to train machine learning models, the subjective elements central to machine learning modelling can go underrecognized —or, worse, ignored —leading to problematic content. Article author Vicki Boykis illustrates this ethical issue by describing the mislabeling of "the person subtree of ImageNet," where, in 2019, most of the dataset was disabled to remedy offensive image labelling. In short, data set creation for machine learning shows that, ethically, the reach of academic work (and corporate interests) can exceed its grasp of knowledge mobilization for the betterment of technology and society. ``` diff --git a/02_activities/assignments/DC_Cohort/Assignment2_Prompt1_ERD.png b/02_activities/assignments/DC_Cohort/Assignment2_Prompt1_ERD.png new file mode 100644 index 000000000..5dab93543 Binary files /dev/null and b/02_activities/assignments/DC_Cohort/Assignment2_Prompt1_ERD.png differ diff --git a/02_activities/assignments/DC_Cohort/Assignment2_Prompt2_ERD.png b/02_activities/assignments/DC_Cohort/Assignment2_Prompt2_ERD.png new file mode 100644 index 000000000..3f73bbee8 Binary files /dev/null and b/02_activities/assignments/DC_Cohort/Assignment2_Prompt2_ERD.png differ diff --git a/02_activities/assignments/DC_Cohort/Assignment2_Prompt3_ERD.png b/02_activities/assignments/DC_Cohort/Assignment2_Prompt3_ERD.png new file mode 100644 index 000000000..37ffc30ea Binary files /dev/null and b/02_activities/assignments/DC_Cohort/Assignment2_Prompt3_ERD.png differ diff --git a/02_activities/assignments/DC_Cohort/assignment1.sql b/02_activities/assignments/DC_Cohort/assignment1.sql index c992e3205..a1e25acee 100644 --- a/02_activities/assignments/DC_Cohort/assignment1.sql +++ b/02_activities/assignments/DC_Cohort/assignment1.sql @@ -4,67 +4,113 @@ --SELECT /* 1. Write a query that returns everything in the customer table. */ - - +SELECT customer_id, customer_first_name, customer_last_name, customer_postal_code +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 customer_id, customer_last_name, customer_first_name, customer_postal_code +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 IN (4,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 +-- option 1 +SELECT product_id, vendor_id, market_date, customer_id, quantity, cost_to_customer_per_qty, transaction_time, (quantity*cost_to_customer_per_qty) AS price +FROM customer_purchases +WHERE customer_id = 8 OR customer_id = 9 +AND customer_id = 9 OR customer_id = 10 -- option 2 - - +SELECT product_id, vendor_id, market_date, customer_id, quantity, cost_to_customer_per_qty, transaction_time, (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 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 product_id, product_name +, CASE WHEN product_qty_type = 'unit' THEN 'unit' + ELSE 'bulk' + END AS prod_qty_type_condensed +, CASE WHEN product_name LIKE '%pepper%' + 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 +v.vendor_id, +vendor_name, +vendor_type, +vendor_owner_first_name, +vendor_owner_last_name, +booth_number, +market_date +FROM vendor AS v +INNER JOIN vendor_booth_assignments AS vb + ON v.vendor_id = vb.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 +COUNT(booth_number) +, vendor_id +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 +cp.customer_id +--,product_id +--,quantity +--,cost_to_customer_per_qty +,customer_last_name +,customer_first_name +--,market_date +--,transaction_time +,SUM(quantity*cost_to_customer_per_qty) AS purchase_total +FROM customer_purchases AS cp +LEFT JOIN customer AS c + ON cp.customer_id = c.customer_id +GROUP BY cp.customer_id +HAVING purchase_total > 2000 +ORDER BY customer_last_name, customer_first_name --Temp Table /* 1. Insert the original vendor table into a temp.new_vendor and then add a 10th vendor: @@ -77,7 +123,30 @@ 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) */ +-- if a table named new_vendor exists, delete it, other do NOTHING +DROP TABLE IF EXISTS temp.new_vendor + +--make the temporary new_vendor table +CREATE TABLE temp.new_vendor AS + +-- define the table +SELECT * +FROM vendor; + +-- put the temp.new_vendor into temp.new_new_vendor + +-- if a table named new_new_vendor exists, delete it, other do NOTHING +DROP TABLE IF EXISTS temp.new_new_vendor; + +-- make the temporary new_new_vendor table +CREATE TABLE temp.new_new_vendor AS + +SELECT * +FROM temp.new_vendor; +-- add a single row of additonal data (see: https://www.w3schools.com/sql/sql_insert.asp) +INSERT INTO temp.new_new_vendor +VALUES (10,'Thomass Superfood Store','Fresh Focused','Thomas','Rosenthal'); -- Date diff --git a/02_activities/assignments/DC_Cohort/assignment2.sql b/02_activities/assignments/DC_Cohort/assignment2.sql index 5ad40748a..083414ce3 100644 --- a/02_activities/assignments/DC_Cohort/assignment2.sql +++ b/02_activities/assignments/DC_Cohort/assignment2.sql @@ -20,6 +20,9 @@ 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 +product_name || ', ' || coalesce(product_size, '')|| ' (' || coalesce(product_qty_type, 'unit') || ')' +FROM product; --Windowed Functions @@ -32,18 +35,37 @@ each new market date for each customer, or select only the unique market dates p (without purchase details) and number those visits. HINT: One of these approaches uses ROW_NUMBER() and one uses DENSE_RANK(). */ - +SELECT +market_date +,customer_id +,ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date) AS [customer_visit] +FROM customer_purchases +GROUP BY market_date, customer_id; /* 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 +market_date +,customer_id + +FROM ( + SELECT + market_date + ,customer_id + ,ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date DESC) AS [customer_visit] + FROM customer_purchases +) x +WHERE x.customer_visit = 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 * +,COUNT(product_id) OVER(PARTITION BY customer_id, product_id ORDER BY product_id,customer_id) AS [times_product_purchased] +FROM customer_purchases; -- String manipulations /* 1. Some product names in the product table have descriptions like "Jar" or "Organic". @@ -57,11 +79,21 @@ 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 * + , TRIM(NULLIF(SUBSTR(product_name, INSTR(product_name, '-') + 1), product_name)) AS description +FROM product; +-- work inside out; remember to add 'one' to substring the product name, to capture string characters one position right of the hythen; experiment with order of commands; check https://www.w3schools.com/sql/func_mysql_nullif.asp /* 2. Filter the query to show any product_size value that contain a number with REGEXP. */ +SELECT * + , TRIM(NULLIF(SUBSTR(product_name, INSTR(product_name, '-') + 1), product_name)) AS description +FROM product + +WHERE product_size REGEXP '\d' +--located REGEX command in regexr.com: character classes > digit > example (for syntax) -- UNION /* 1. Using a UNION, write a query that displays the market dates with the highest and lowest total sales. @@ -74,7 +106,41 @@ HINT: There are a possibly a few ways to do this query, but if you're struggling with a UNION binding them. */ +-- Use a CTE to calculate sum of sales by market date using customer_purchases table +WITH sales_by_date AS ( + SELECT + cp.market_date, + SUM(quantity * cost_to_customer_per_qty) AS sales + FROM customer_purchases cp + GROUP BY cp.market_date +), +-- Use a second CTE to rank customer sales by market date, create best_day and worst_day sales by date +sales_ranking AS ( + SELECT + market_date, + sales, + ROW_NUMBER() OVER (ORDER BY sales DESC) AS best_day, + ROW_NUMBER() OVER (ORDER BY sales ASC) AS worst_day + FROM sales_by_date +) +-- Use UNION command to stack the sales_ranking CTEs for best_day and worst_day of customer sales +-- Generate the "best day" variable value +SELECT + market_date, + sales, + 'Best Day' AS sales_type +FROM sales_ranking +WHERE best_day = 1 + +UNION +-- Generate the "worst day" variable value +SELECT + market_date, + sales, + 'Worst Day' AS sales_type +FROM sales_ranking +WHERE worst_day = 1; /* SECTION 3 */ @@ -89,7 +155,48 @@ 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). */ - +-- Create tempory table with required vendor and product columns called new_vendor_inventory: (DISTINCT) vendor_id, product_id, original_price from vendor_inventory +-- if a table named new_vendor_inventory exists, delete it, other do NOTHING +DROP TABLE IF EXISTS temp.new_vendor_inventory; + +--make the table +CREATE TABLE temp.new_vendor_inventory AS + +-- definition of the table +SELECT DISTINCT + vi.vendor_id + ,product_id + ,original_price + ,original_price*5 as total_vendor_sales +FROM vendor_inventory vi; + +-- Left join new_vendor_inventory temp table with vendor_name from vendor table on vi.vendor_id, to add vendor_name colum to the tempory table; +-- Left join product_name from product table on product_id, to add product names to the temporary table + +DROP TABLE IF EXISTS temp.new_new_vendor_inventory; + +CREATE TABLE temp.new_new_vendor_inventory AS + +SELECT + nvi.vendor_id + ,nvi.product_id + ,nvi.total_vendor_sales + ,v.vendor_name + ,p.product_name +FROM temp.new_vendor_inventory as nvi +LEFT JOIN vendor as v + ON nvi.vendor_id = v.vendor_id +LEFT JOIN product as p + ON nvi.product_id = p.product_id; + +-- Cross join vendor products from new_new_vendor_inventory with all 26 customers on record in customer table +SELECT + nnvi.vendor_name + ,nnvi.product_name + ,SUM(nnvi.total_vendor_sales) AS total_sales +FROM customer c +CROSS JOIN temp.new_new_vendor_inventory nnvi +GROUP BY nnvi.vendor_name, nnvi.product_name; -- INSERT /*1. Create a new table "product_units". @@ -97,19 +204,30 @@ 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`. */ +-- For information on 'CURRENT_TIMESTAMP', I referred to: https://www.geeksforgeeks.org/postgresql/postgresql-current_timestamp-function/ +DROP TABLE IF EXISTS temp.product_units; +CREATE TABLE temp.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 temp.product_units +VALUES(24,'Chocolate Cake','2 lbs',3,'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 temp.product_units +WHERE product_id = 24; +SELECT * +FROM temp.product_units -- UPDATE /* 1.We want to add the current_quantity to the product_units table. @@ -128,6 +246,44 @@ 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. */ +ALTER TABLE temp.product_units +ADD current_quantity INT; - +-- Obtain the most recent quantity per product_id in vendor_inventory table using a subquery +SELECT + market_date + ,quantity, + ,product_id +FROM ( + SELECT + market_date + ,quantity + ,product_id + ,DENSE_RANK() OVER(PARTITION BY product_id ORDER BY market_date DESC) AS [dense_rank] + FROM vendor_inventory +) +WHERE dense_rank = 1 + +-- Use UPDATE to change the current_quantity column to the last quantity value using query code developed above +UPDATE temp.product_units +SET current_quantity = ( + SELECT COALESCE(quantity, 0) -- return non-null quantity values from the vendor_inventory table, or if quantity value is null, return a zero + FROM ( + SELECT + market_date + ,product_id + ,quantity + ,DENSE_RANK() OVER(PARTITION BY product_id ORDER BY market_date DESC) AS [dense_rank] + FROM vendor_inventory +) ranked -- alias for subquery + WHERE dense_rank = 1 + AND ranked.product_id = product_units.product_id -- match the subquery and temp table product_id by row +) -- end of SET function +-- Cannot specify a particular row; therefore, specify all selected rows from the vendor inventory +WHERE product_units.product_id IN (SELECT DISTINCT product_id FROM vendor_inventory) + +-- Change current_quantity null values to 0 +UPDATE temp.product_units +SET current_quantity = 0 +WHERE current_quantity IS NULL; diff --git a/02_activities/assignments/DC_Cohort/farmers-db_logical-diagram.drawio b/02_activities/assignments/DC_Cohort/farmers-db_logical-diagram.drawio new file mode 100644 index 000000000..af0cad48d --- /dev/null +++ b/02_activities/assignments/DC_Cohort/farmers-db_logical-diagram.drawio @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/04_this_cohort/live_code/DC/module_3/arithmitic.sql b/04_this_cohort/live_code/DC/module_3/arithmitic.sql index eb056cf1e..4467b0e00 100644 --- a/04_this_cohort/live_code/DC/module_3/arithmitic.sql +++ b/04_this_cohort/live_code/DC/module_3/arithmitic.sql @@ -16,3 +16,4 @@ WHERE vendor_id % 2 = 0; SELECT * FROM vendor WHERE vendor_id % 3 = 0; +-- hello \ No newline at end of file diff --git a/sql b/sql new file mode 100644 index 000000000..e69de29bb