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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 27 additions & 2 deletions 02_activities/assignments/design_a_logical_model.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,54 @@
# Participant Name : Sidra Zain
# Assignment 1: Design a Logical Model

## Question 1
Create 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. 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/).

![Logical model for Bookstore](../../sql/02_activities/assignments/images/Lgical model for bookstore.png)

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

Question 1 and Question 2 are combined in one ERD.

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

![Type 1 and Type 2 SCD](../../sql/02_activities/assignments/images/Type 1 and Type 2 SCD.png)

Bonus: Are there privacy implications to this, why or why not?
```
Your answer...
Both architectures present privacy implications, but Type 2 poses more significant challenges due to the retention of Addresses. Bookstore must implement robust data protection measures, provide clear privacy policies, and ensure compliance with applicable regulations to manage these implications effectively. Additionally, offering customers transparency and control over their data can help build trust and mitigate privacy concerns.
```

## Question 4
Review the AdventureWorks Schema [here](https://i.stack.imgur.com/LMu4W.gif)

Highlight at least two differences between it and your ERD. Would you change anything in yours?
```
Your answer...
The AdventureWorks database is a comprehensive schema used for demonstrating various aspects of business data management. Here are two notable differences between the AdventureWorks schema and the ERD I provided for a small bookstore:

Differences:

AdventureWorks:

1. This schema is much larger and more complex, featuring multiple entities like Production, purchasing, Sales, persons and more. It includes various dimensions catering to larger-scale business operations.
2. It uses a highly normalized approach, often separating information into numerous related tables to minimize data redundancy. For example, there are separate tables for Address, Contact Information, and other dimensions.

Bookstore ERD:

1. The bookstore schema is simpler, focusing on core entities relevant to a small business. It primarily tracks Employees, Customers, Orders, Sales, and Books, with less emphasis on extensive attributes or multiple product categories.
2. While still maintaining some normalization, the bookstore schema is more straightforward, with fewer separate tables. For instance, customer address details are stored directly in the Customers table rather than in a separate Addresses table.

Potential Changes to the Bookstore ERD:

To align more closely with best practices seen in the AdventureWorks schema, I would consider normalizing the Customer table further. This could involve creating a separate Addresses table to manage customer addresses. This way, a customer could have multiple addresses (billing, shipping, etc.), and it would avoid redundancy.

In AdventureWorks, products are often categorized and linked to various attributes (like size, color, etc.). For the bookstore ERD, I might consider adding a Categories table to categorize books (e.g., Fiction, Non-Fiction, Children's), which would enhance the organization and querying capabilities of the book data.
```

# Criteria
Expand Down
2 changes: 2 additions & 0 deletions 02_activities/homework/homework_1.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ A logical data model must contain:
- column names
- relationship type

![Logical_data_model.png](./images/Homework_1.png)

Please do not pick the exact same tables that I have already diagramed. For example, you shouldn't diagram the relationship between `product` and `product_category`, but you could diagram `product` and `customer_purchases`.

**A few hints**:
Expand Down
46 changes: 43 additions & 3 deletions 02_activities/homework/homework_2.sql
Original file line number Diff line number Diff line change
@@ -1,42 +1,82 @@
--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. */
-- option 1

SELECT *
FROM customer_purchases
WHERE product_id = 4 OR product_id = 9;

-- option 2

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 vendor 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 vendor_id >= 8 AND vendor_id <= 10;

-- option 2

SELECT *, quantity*cost_to_customer_per_qty as [price]
from customer_purchases
WHERE vendor_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 '%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 *
FROM vendor as v
INNER JOIN vendor_booth_assignments as vba
on v.vendor_id = vba.vendor_id
ORDER by vendor_name, market_date;
37 changes: 34 additions & 3 deletions 02_activities/homework/homework_3.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,25 @@
/* 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 booth_number, vendor_id,
count(vendor_id) as vendor_rented_booth
FROM vendor_booth_assignments
GROUP by booth_number
ORDER by vendor_rented_booth;

/* 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, customer_last_name, customer_first_name
,sum(quantity*cost_to_customer_per_qty) as cost
FROM customer as c
join customer_purchases as cp
on c.customer_id = cp.customer_id
GROUP by c.customer_id
HAVING cost > 2000;

--Temp Table
/* 1. Insert the original vendor table into a temp.new_vendor and then add a 10th vendor:
Expand All @@ -24,17 +34,38 @@ When inserting the new vendor, you need to appropriately align the columns to be
VALUES(col1,col2,col3,col4,col5)
*/


DROP TABLE if EXISTS new_vendor;
CREATE TEMP TABLE temp.new_vendor As
SELECT *
FROM vendor;
INSERT INTO new_vendor
VALUES(10,'Thomass Superfood Store', 'Fresh Focused store', 'Thomas',' Rosenthal');
SELECT *
FROM new_vendor;

-- 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, quantity, cost_to_customer_per_qty, market_date,
strftime('%Y', market_date) as year,
strftime('%m',market_date) as month
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, quantity, cost_to_customer_per_qty, market_date,
sum(quantity*cost_to_customer_per_qty) as total_money_spent,
strftime('%Y', market_date) as year,
strftime('%m',market_date) as month
FROM customer_purchases
WHERE
strftime('%Y', market_date) = '2022' AND
strftime('%m',market_date) = '04'
GROUP by customer_id, month, year;
64 changes: 59 additions & 5 deletions 02_activities/homework/homework_4.sql
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,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') || ')' as List_of_products
FROM product;


--Windowed Functions
Expand All @@ -30,16 +32,34 @@ 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
customer_id,
market_date,
row_number() OVER (PARTITION by customer_id ORDER by market_date) as customer_market_visit
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 customer_market_visit
FROM customer_purchases
)x
WHERE x.customer_market_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 DISTINCT customer_id, product_id,
COUNT() OVER (PARTITION by customer_id, product_id) as customer_purchase_count
FROM customer_purchases;


-- String manipulations
Expand All @@ -54,11 +74,20 @@ 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 *,
CASE
WHEN INSTR(product_name,'-') > 0
THEN
LTRIM(RTRIM(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.
Expand All @@ -70,6 +99,31 @@ 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. */


DROP TABLE if EXISTS Sales_values;
CREATE TEMP TABLE Sales_values As
SELECT *,
sum(quantity * cost_to_customer_per_qty) as total_sales
from customer_purchases
GROUP by market_date;

SELECT market_date, total_sales, worst_day as ranks
FROM
(
SELECT *
,rank() OVER (ORDER by total_sales ASC) as worst_day
from Sales_values
)
where worst_day = 1

UNION

SELECT market_date,total_sales, best_day as ranks
FROM
(
SELECT *
,rank() OVER (ORDER by total_sales DESC) as best_day
FROM Sales_values
)
WHERE best_day = 1;


Loading