Skip to content
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
192 changes: 140 additions & 52 deletions 02_activities/assignments/Assignment2.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
# Assignment 2: Design a Logical Model and Advanced SQL
Assignment 2: Design a Logical Model and Advanced SQL
Please review our [Assignment Submission Guide](https://github.com/UofT-DSI/onboarding/blob/main/onboarding_documents/submissions.md)for detailed instructions on how to format, branch, and submit your work. Following these guidelines is crucial for your submissions to be evaluated correctly.

🚨 **Please review our [Assignment Submission Guide](https://github.com/UofT-DSI/onboarding/blob/main/onboarding_documents/submissions.md)** 🚨 for detailed instructions on how to format, branch, and submit your work. Following these guidelines is crucial for your submissions to be evaluated correctly.

#### Submission Parameters:
* Submission Due Date: `August 17, 2025`
* Weight: 70% of total grade
* The branch name for your repo should be: `assignment-two`
Expand All @@ -21,9 +20,8 @@ Checklist:

If you encounter any difficulties or have questions, please don't hesitate to reach out to our team via our Slack at `#cohort-6-help`. Our Technical Facilitators and Learning Support staff are here to help you navigate any challenges.

***

## Section 1:

You can start this section following *session 1*, but you may want to wait until you feel comfortable wtih basic SQL query writing.

Steps to complete this part of the assignment:
Expand All @@ -32,9 +30,7 @@ Steps to complete this part of the assignment:
- Write, within this markdown file, an answer to Prompt 3


### Design a Logical Model

#### Prompt 1
Design a logical model for a small bookstore. 📚

At the minimum it should have employee, order, sales, customer, and book entities (tables). Determine sensible column and table design based on what you know about these concepts. Keep it simple, but work out sensible relationships to keep tables reasonably sized.
Expand All @@ -43,23 +39,22 @@ Additionally, include a date table.

There are several tools online you can use, I'd recommend [Draw.io](https://www.drawio.com/) or [LucidChart](https://www.lucidchart.com/pages/).

**HINT:** You do not need to create any data for this prompt. This is a logical model (ERD) only.
You do not need to create any data for this prompt. This is a logical model (ERD) only.


#### Prompt 2
We want to create employee shifts, splitting up the day into morning and evening. Add this to the ERD.

#### Prompt 3

The store wants to keep customer addresses. Propose two architectures for the CUSTOMER_ADDRESS table, one that will retain changes, and another that will overwrite. Which is type 1, which is type 2?

**HINT:** search type 1 vs type 2 slowly changing dimensions.
search type 1 vs type 2 slowly changing dimensions.

```
Your answer...
```

***
![alt text](image-1.png)

![alt text](image-2.png)
![alt text](image-3.png)

## Section 2:
You can start this section following *session 4*.

Steps to complete this part of the assignment:
Expand All @@ -69,57 +64,102 @@ Steps to complete this part of the assignment:
- Complete each question


### Write SQL

#### COALESCE
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
```
product_name || ', ' ||
COALESCE(product_size, '') || ' (' ||
COALESCE(product_qty_type, 'unit') || ')'
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.
: 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
product_name || ', ' ||
COALESCE(product_size, '') || ' (' ||
COALESCE(product_qty_type, 'unit') || ')'
FROM product;

<div align="center">-</div>

#### Windowed Functions
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().
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.

<div align="center">-</div>

#### String manipulations
SELECT
v.vendor_id,
p.product_id,
(5 * c.cust_count * p.cost_to_customer_per_qty) AS total_revenue
FROM vendor_inventory vi
JOIN vendor v ON vi.vendor_id = v.vendor_id
JOIN product p ON vi.product_id = p.product_id
CROSS JOIN (
SELECT COUNT(*) AS cust_count
FROM customer
) c;


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.
you might need to use INSTR(product_name,'-') to find the hyphens. INSTR will help split the column.
SELECT
product_name,
TRIM(
CASE
WHEN INSTR(product_name, '-') > 0
THEN SUBSTR(product_name, INSTR(product_name, '-') + 1)
END
) AS description
FROM product;


<div align="center">-</div>

#### 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.
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_per_date AS (
SELECT
market_date,
SUM(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 sales_rank_desc,
RANK() OVER (ORDER BY total_sales ASC) AS sales_rank_asc
FROM sales_per_date
)
SELECT market_date, total_sales, 'Highest Sales' AS sales_type
FROM ranked_sales
WHERE sales_rank_desc = 1

UNION

SELECT market_date, total_sales, 'Lowest Sales' AS sales_type
FROM ranked_sales
WHERE sales_rank_asc = 1;


***

## Section 3:
You can start this section following *session 5*.

Steps to complete this part of the assignment:
Expand All @@ -128,36 +168,84 @@ Steps to complete this part of the assignment:
- or, from your local forked repository
- Complete each question

### Write SQL

#### 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.
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.

: 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_id,
p.product_id,
(5 * c.cust_count * p.cost_to_customer_per_qty) AS total_revenue
FROM vendor_inventory vi
JOIN vendor v ON vi.vendor_id = v.vendor_id
JOIN product p ON vi.product_id = p.product_id
CROSS JOIN (
SELECT COUNT(*) AS cust_count
FROM customer
) c;

**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).

<div align="center">-</div>

#### 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`.

2. Using `INSERT`, add a new row to the product_unit table (with an updated timestamp). This can be any product you desire (e.g. add another record for Apple Pie).
product_id,
product_name,
product_size,
product_qty_type,
cost_to_customer_per_qty,
snapshot_timestamp
)
VALUES (
999,
'Apple Pie',
'Large',
'unit',
12.99,
CURRENT_TIMESTAMP


<div align="center">-</div>

#### 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](https://imgflip.com/i/8iq872).
If you don't specify a WHERE clause, [you are going to have a bad time](https://imgflip.com/i/8iq872).
DELETE FROM product_units
WHERE product_name = 'Apple Pie'
AND snapshot_timestamp < (
SELECT MAX(snapshot_timestamp)
FROM product_units
WHERE product_name = 'Apple Pie'
);

ALTER TABLE product_units
ADD current_quantity INT;

<div align="center">-</div>

#### 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.
Then, using `UPDATE`, change the current_quantity equal to the last*`quantity` value from the vendor_inventory details.

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 pu
SET current_quantity = (
SELECT COALESCE(vi.quantity, 0)
FROM vendor_inventory vi
WHERE vi.product_id = pu.product_id
ORDER BY vi.last_updated DESC
LIMIT 1
)
WHERE pu.product_id IN (
SELECT DISTINCT product_id
FROM vendor_inventory
);
WITH sales_per_date AS (
SELECT
market_date,
SUM(sale_amount) AS total_sales
FROM sales
GROUP BY market_date
)
Binary file added 02_activities/assignments/image-1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added 02_activities/assignments/image-2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added 02_activities/assignments/image-3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added 02_activities/assignments/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added 02_activities/assignments/sql1.pdf
Binary file not shown.
91 changes: 91 additions & 0 deletions 02_activities/assignments/sql1.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
SELECT *
FROM customer;

SELECT *
FROM customer
ORDER BY customer_last_name, customer_first_name
LIMIT 10;

SELECT *
FROM customer_purchases
WHERE product_id IN (4, 9);

SELECT *
FROM vendor_inventory
WHERE quantity>5 and original_price>5;

SELECT customer_id
FROM customer_purchases
WHERE quantity>2.5 and cost_to_customer_per_qty>2.5;

SELECT customer_id
FROM customer_purchases
WHERE quantity BETWEEN 2.5 AND 3.5;

SELECT product_id,product_name,
CASE WHEN product_qty_type = 'unit' THEN 'unit'
ELSE 'bulk'
END AS prod_qty_type_condensed
FROM product;

SELECT product_id,product_name,
CASE WHEN LOWER(product_name) LIKE '%pepper%' THEN 1
ELSE 0
END AS pepper_flag
FROM product;

SELECT v.vendor_name,
vba.market_date,

v.*,
vba.*
FROM
vendor v
INNER JOIN
vendor_booth_assignments vba ON v.vendor_id = vba.vendor_id
ORDER BY
v.vendor_name ASC,
vba.market_date ASC;

SELECT vendor_id,
COUNT(*) AS booth_rental_count
FROM vendor_booth_assignments
GROUP BY vendor_id
ORDER BY booth_rental_count DESC;

SELECT
c.customer_id,
SUM(cp.quantity) AS TotalSpent
FROM customer AS c
JOIN customer_purchases AS cp
ON c.customer_id = cp.customer_id
GROUP BY
c.customer_id
HAVING TotalSpent > 2000
ORDER BY
c.customer_id;



CREATE TABLE temp.new_vendor AS
SELECT *
FROM vendor;
INSERT INTO temp.new_vendor (vendor_id, vendor_name, vendor_type, owner_first_name, owner_last_name)
VALUES (10, 'Thomass Superfood Store', 'Fresh Focused store', 'Thomas', 'Rosenthal');

SELECT
customer_id,
strftime('%m', purchase_date) AS month,
strftime('%Y', purchase_date) AS year
FROM customer_purchases;





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;