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
51 changes: 29 additions & 22 deletions 02_activities/homework/homework_1.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,75 +4,82 @@
- Weight: 8% of total grade

## Get to know the farmersmarket.db

Steps to complete this part of the homework:

#### 1) Load Database

- Open DB Browser for SQLite
- Go to File > Open Database
- Navigate to your farmersmarket.db
- This will be wherever you cloned the GH Repo (within the **SQL** folder)
- ![db_browser_for_sqlite_choose_db.png](./images/01_db_browser_for_sqlite_choose_db.png)
- Navigate to your farmersmarket.db
- This will be wherever you cloned the GH Repo (within the **SQL** folder)
- ![db_browser_for_sqlite_choose_db.png](./images/01_db_browser_for_sqlite_choose_db.png)

#### 2) Configure your windows

By default, DB Browser for SQLite has three windows, with four tabs in the main window and three tabs in the bottom right window

- Window 1: Main Window (Centre)
- Stay in the Database Structure tab for now
- Stay in the Database Structure tab for now
- Window 2: Edit Database Cell (Top Right)
- Window 3: Remote (Bottom Right)
- Switch this to DB Schema tab (very bottom)
- Switch this to DB Schema tab (very bottom)

Your screen should look like this (or very similar)
![db_browser_for_sqlite.png](./images/01_db_browser_for_sqlite.png)

#### 3) The farmersmarket.db

There are 10 tables in the Main Window:
1) booth
2) customer
3) customer_purchases
4) market_date_info
5) product
6) product_category
7) vendor
8) vendor_booth_assignments
9) vendor_inventory
10) zip_data

Switch to the Browse Data tab, booth is selected by default
![01_the_browse_data_tab.png](./images/01_the_browse_data_tab.png)
1. booth
2. customer
3. customer_purchases
4. market_date_info
5. product
6. product_category
7. vendor
8. vendor_booth_assignments
9. vendor_inventory
10. zip_data

Switch to the Browse Data tab, booth is selected by default
![01_the_browse_data_tab.png](./images/01_the_browse_data_tab.png)

Using the table drop down at the top left, explore some of the contents of the database
![01_the_table_drop_down_at_the_top_left.png](./images/01_the_table_drop_down_at_the_top_left.png)

Move on to the Logical Data Model task when you have looked through the tables


## Logical Data Model

Recall during the module:

I diagramed the following four tables:

- product
- product_category
- vendor
- vendor_inventory

![01_farmers_market_logical_model_partial.png](./images/01_farmers_market_logical_model_partial.png)


Your task: choose two tables and create a logical data model. There are lots of tools you can do this (including drawing this by hand), but I'd recommend [Draw.io](https://www.drawio.com/) or [LucidChart](https://www.lucidchart.com/pages/).
Your task: choose two tables and create a logical data model. There are lots of tools you can do this (including drawing this by hand), but I'd recommend [Draw.io](https://www.drawio.com/) or [LucidChart](https://www.lucidchart.com/pages/).

A logical data model must contain:

- table name
- column names
- relationship type

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**:

- You will need to use the Browse Data tab in the main window to figure out the relationship types.
- You can't diagram tables that don't share a common column
- These are the tables that are connected
- ![01_farmers_market_conceptual_model.png](./images/01_farmers_market_conceptual_model.png)
- These are the tables that are connected
- ![01_farmers_market_conceptual_model.png](./images/01_farmers_market_conceptual_model.png)
- The column names can be found in a few spots (DB Schema window in the bottom right, the Database Structure tab in the main window by expanding each table entry, at the top of the Browse Data tab in the main window)

![image info](./images/homework_1.png)
39 changes: 33 additions & 6 deletions 02_activities/homework/homework_2.sql
Original file line number Diff line number Diff line change
@@ -1,42 +1,69 @@
--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 IN (4,9)
-- option 2
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 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 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 *
FROM vendor AS v
INNER JOIN vendor_booth_assignments AS vba
ON v.vendor_id = vba.vendor_id
ORDER BY v.vendor_name, vba.market_date

--alternative version, so that vendor_id isn't repeated
SELECT v.*, vba.market_date, vba.booth_number
FROM vendor AS v INNER JOIN vendor_booth_assignments AS vba
ON v.vendor_id = vba.vendor_id ORDER BY v.vendor_name, vba.market_date
47 changes: 45 additions & 2 deletions 02_activities/homework/homework_3.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,31 @@
/* 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 v.vendor_id,
v.vendor_name,
Count(vba.vendor_id)AS booths_rented
FROM vendor_booth_assignments vba
JOIN vendor v
ON vba.vendor_id = v.vendor_id
GROUP BY v.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_last_name,
c.customer_first_name,
sum(cp.quantity * cp.cost_to_customer_per_qty) AS customer_total_spend
FROM customer c
JOIN customer_purchases cp
ON cp.customer_id = c.customer_id
GROUP BY c.customer_id
HAVING customer_total_spend > 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:
Expand All @@ -23,7 +39,19 @@ 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;

CREATE TEMP TABLE temp.new_vendor AS

SELECT *
FROM vendor;

INSERT INTO temp.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');

SELECT *
FROM temp.new_vendor;


-- Date
Expand All @@ -32,9 +60,24 @@ VALUES(col1,col2,col3,col4,col5)
HINT: you might need to search for strfrtime modifers sqlite on the web to know what the modifers for month
and year are! */

SELECT customer_id,
Strftime('%m', market_date) AS month,
Strftime('%Y', market_date) AS 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,
Strftime('%m', market_date) AS month,
Strftime('%Y', market_date) AS year,
Sum(quantity * cost_to_customer_per_qty) AS money_spent
FROM customer_purchases
WHERE STRFTIME('%Y-%m', market_date) = '2022-04'
--Alternate WHERE clause below
--WHERE month = '04' AND year = '2022'
GROUP BY customer_id, year, month;

73 changes: 68 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') || ')'
FROM product;


--Windowed Functions
Expand All @@ -30,16 +32,42 @@ 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(). */

-- WITH ROW_NUMBER()
SELECT
ROW_NUMBER() OVER (PARTITION by customer_id ORDER BY market_date) AS visit,
customer_id,market_date
FROM customer_purchases;

----Version Below Ranks visit based on customer_id,market_date and transaction_time
--SELECT
--ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date, transaction_time) AS visit
--,customer_id, market_date, transaction_time
--FROM customer_purchases;

-- USING DENSE_RANK()
SELECT
DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY market_date) AS 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
ROW_NUMBER() OVER (PARTITION by customer_id ORDER BY market_date DESC) AS visit,
customer_id,market_date
FROM customer_purchases) x
WHERE x.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(*) OVER (PARTITION BY customer_id, product_id) AS purchased_times,*
FROM customer_purchases;


-- String manipulations
Expand All @@ -54,11 +82,26 @@ 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,
CASE
WHEN INSTR(product_name,'-') > 0
THEN LTRIM(RTRIM(SUBSTR(product_name,INSTR(product_name,'-')+1)))
--Altrenate approach below
--THEN LTRIM(RTRIM(SUBSTR(product_name,(INSTR(product_name,'-')-length(product_name)))))
ELSE NULL
END 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,
CASE
WHEN INSTR(product_name,'-') > 0
THEN LTRIM(RTRIM(SUBSTR(product_name,INSTR(product_name,'-')+1)))
ELSE NULL
END AS description
FROM product WHERE product_size REGEXP '[0-9]';
-- REGEXP'[0-9]' fiters any values that contain a number

-- UNION
/* 1. Using a UNION, write a query that displays the market dates with the highest and lowest total sales.
Expand All @@ -70,6 +113,26 @@ 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 daily_sales AS(
SELECT market_date
,SUM(quantity * cost_to_customer_per_qty) AS total_sales
FROM customer_purchases
GROUP BY market_date
),highest_lowest_daily_sales AS(
SELECT * ,
RANK() OVER(ORDER BY total_sales DESC) AS highs,
RANK() OVER(ORDER BY total_sales ASC) AS lows
FROM daily_sales
)

SELECT 'Best Day' AS Best_Worst, market_date, total_sales
FROM highest_lowest_daily_sales
WHERE highs=1

UNION

SELECT 'Worst Day' AS Best_Worst, market_date, total_sales
FROM highest_lowest_daily_sales
WHERE lows=1;


Loading