Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Homeworks #2

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
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
1 change: 1 addition & 0 deletions 03_homework/homework_1.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,4 @@ Please do not pick the exact same tables that I have already diagramed. For exam
- ![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)

![Fredy Rincon's Logical Data Model](image.png)
3 changes: 3 additions & 0 deletions 03_homework/homework_2.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,6 @@

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

[Link to Fredy's homework_2.sql](homework_2.sql)
[Link to Fredy's homework_2.txt](homework_2.txt)
65 changes: 65 additions & 0 deletions 03_homework/homework_2.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
-- SELECT 1: Query to return everything in the customer table:

SELECT * FROM customer;

-- SELECT 2: Query to display all ten columns and ten rows from the customer table, sorted by customer_last_name and then customer_first_name:

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


-- WHERE 1: Query to return all customer purchases of product IDs 4 and 9:

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


-- WHERE 2a: Query to return all customer purchases and a new calculated column 'price', filtered by vendor IDs between 8 and 10 using AND:

SELECT *, (quantity * cost_to_customer_per_qty) AS price
FROM customer_purchases
WHERE vendor_id >= 8 AND vendor_id <= 10;


-- WHERE 2b: Query to return all customer purchases and a new calculated column 'price', filtered by vendor IDs between 8 and 10 using BETWEEN:

SELECT *, (quantity * cost_to_customer_per_qty) AS price
FROM customer_purchases
WHERE vendor_id BETWEEN 8 AND 10;


-- CASE 1: Query to output product_id, product_name, and add a column called prod_qty_type_condensed:

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


-- CASE 2: Query to add a column called pepper_flag:

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


-- JOIN: Query to INNER JOIN the vendor table to the vendor_booth_assignments table on the vendor_id field and sort by vendor_name, then market_date:

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

65 changes: 65 additions & 0 deletions 03_homework/homework_2.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
-- SELECT 1: Query to return everything in the customer table:

SELECT * FROM customer;

-- SELECT 2: Query to display all ten columns and ten rows from the customer table, sorted by customer_last_name and then customer_first_name:

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


-- WHERE 1: Query to return all customer purchases of product IDs 4 and 9:

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


-- WHERE 2a: Query to return all customer purchases and a new calculated column 'price', filtered by vendor IDs between 8 and 10 using AND:

SELECT *, (quantity * cost_to_customer_per_qty) AS price
FROM customer_purchases
WHERE vendor_id >= 8 AND vendor_id <= 10;


-- WHERE 2b: Query to return all customer purchases and a new calculated column 'price', filtered by vendor IDs between 8 and 10 using BETWEEN:

SELECT *, (quantity * cost_to_customer_per_qty) AS price
FROM customer_purchases
WHERE vendor_id BETWEEN 8 AND 10;


-- CASE 1: Query to output product_id, product_name, and add a column called prod_qty_type_condensed:

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


-- CASE 2: Query to add a column called pepper_flag:

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


-- JOIN: Query to INNER JOIN the vendor table to the vendor_booth_assignments table on the vendor_id field and sort by vendor_name, then market_date:

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

2 changes: 2 additions & 0 deletions 03_homework/homework_3.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ To insert the new row use VALUES, specifying the value you want for each column:
2. Using the previous query as a base, determine how much money each customer spent in April 2019. 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!!

[Fredy's SQL Homework_3](homework_3.sql)

33 changes: 33 additions & 0 deletions 03_homework/homework_3.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
--Aggregate Query: Counting Vendor Booth Assignments
SELECT vendor_id, COUNT(*) AS booth_assignment_count
FROM vendor_booth_assignments
GROUP BY vendor_id;

--Aggregate Query: Customers Spending More Than $2000
SELECT c.customer_id, c.customer_first_name, c.customer_last_name, SUM(cp.quantity * cp.cost_to_customer_per_qty) AS total_spent
FROM customer c
JOIN customer_purchases cp ON c.customer_id = cp.customer_id
GROUP BY c.customer_id, c.customer_first_name, c.customer_last_name
HAVING total_spent > 2000
ORDER BY c.customer_last_name, c.customer_first_name;

--Temp Table: Insert New Vendor
CREATE TEMPORARY 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 Query: Extract Month and Year
SELECT customer_id, strftime('%m', market_date) AS month, strftime('%Y', market_date) AS year
FROM customer_purchases;

--Date Query: Customer Spending in April 2019
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) = '2019'
GROUP BY customer_id;
--FREDY RINCON
--uoft-dsi-c3-homework_3-20240517
--uoft-dsi-c3-sql_homework_3-20240517
2 changes: 2 additions & 0 deletions 03_homework/homework_4.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,5 @@ You can either display all rows in the customer_purchases table, with the counte
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.

[Homework_4.sql](homework_4.sql)
143 changes: 143 additions & 0 deletions 03_homework/homework_4.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
-- 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 problem, and 'unit' for the second problem.

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, '') || ', ' ||
COALESCE(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. */
WITH ranked_visits AS (
SELECT
customer_id,
market_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date DESC) as visit_number
FROM
customer_purchases
)
SELECT *
FROM ranked_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,
quantity,
COUNT(*) OVER (PARTITION BY customer_id, product_id) as purchase_count
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, '-') + 2)) as description
FROM
product
WHERE
INSTR(product_name, '-') > 0;

-- 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(quantity * cost_to_customer_per_qty) 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_by_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;



1 change: 1 addition & 0 deletions 03_homework/homework_5.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,6 @@ Then, using `UPDATE`, change the current_quantity equal to the **last** `quantit

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

[Homework_5.sql](homework_5.sql)


Loading