Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
29afc52
Add files via upload
zrasi May 16, 2024
95447f1
Update homework_1.md with my answer
zrasi May 16, 2024
e2b99fd
Update homework_1.md - added my answer
zrasi May 16, 2024
9a10b88
in class code day 3
mrpotatocode May 17, 2024
1891402
Add files via upload
zrasi May 17, 2024
5f37f8e
Add files via upload - completed homework_3
zrasi May 17, 2024
79d3369
minor 04 update
mrpotatocode May 19, 2024
9f05821
Delete transit_shelter_data.csv
mrpotatocode May 19, 2024
2f34d57
minor 04 reference update
mrpotatocode May 19, 2024
197e765
rearrange of 05 content
mrpotatocode May 19, 2024
b955096
Merge pull request #44 from UofT-DSI/slides_05_reorg
RohanAlexander May 20, 2024
9c49770
minor 06 updates
mrpotatocode May 20, 2024
4d23553
fixing think pair share emoji inconsistency
mrpotatocode May 20, 2024
52e3a43
wrong pdf folder fix
mrpotatocode May 20, 2024
c61be3b
in class code class 4
mrpotatocode May 22, 2024
ac4b912
Update homework_5.sql
mrpotatocode May 22, 2024
4cdffe9
Update homework_4.sql
mrpotatocode May 22, 2024
efb6cec
05 codes
mrpotatocode May 23, 2024
9eab248
06 normal forms code
mrpotatocode May 23, 2024
d74edad
Committing changes before merging with remote
zrasi May 23, 2024
2480375
Merge branch 'homework' of https://github.com/zrasi/sql into homework
zrasi May 23, 2024
f322d87
Add files via upload - Completed homework 4
zrasi May 24, 2024
9cced79
Add files via upload - Completed homework 5
zrasi May 24, 2024
5b8e343
Add files via upload - completed homework 5
zrasi May 24, 2024
4067ae3
Update homework_6.md - Completed homework 6
zrasi May 26, 2024
c4644d6
Update homework_6.md - Completed homework 6
zrasi May 26, 2024
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
Binary file modified 01_slides/slides_03.pdf
Binary file not shown.
Binary file modified 01_slides/slides_04.pdf
Binary file not shown.
Binary file modified 01_slides/slides_05.pdf
Binary file not shown.
Binary file modified 01_slides/slides_06.pdf
Binary file not shown.
4 changes: 3 additions & 1 deletion 03_homework/homework_1.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,6 @@ Please do not pick the exact same tables that I have already diagramed. For exam
- 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)


- My answer here:
- https://github.com/zrasi/sql/blob/homework/03_homework/images/Zarrin_sql_homework_1.png
42 changes: 39 additions & 3 deletions 03_homework/homework_2.sql
Original file line number Diff line number Diff line change
@@ -1,42 +1,78 @@
--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 customer_id, customer_first_name, customer_last_name, customer_zip
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 UPPER(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 v
INNER JOIN vendor_booth_assignments vba ON v.vendor_id = vba.vendor_id
ORDER BY v.vendor_name, vba.market_date;
32 changes: 31 additions & 1 deletion 03_homework/homework_3.sql
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
-- 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 vendor_id, COUNT(*) AS booth_rental_count
FROM vendor_booth_assignments
GROUP BY vendor_id;


/* 2. The Farmer’s Market Customer Appreciation Committee wants to give a bumper
Expand All @@ -10,6 +12,16 @@ 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_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
Expand All @@ -23,7 +35,15 @@ 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 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, 'Thomas Superfood Store', 'a Fresh Focused store', 'Thomas', 'Rosenthal');

SELECT * FROM new_vendor;


-- Date
Expand All @@ -32,9 +52,19 @@ 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 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!! */
SELECT customer_id, market_date,
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;

213 changes: 173 additions & 40 deletions 03_homework/homework_4.sql
Original file line number Diff line number Diff line change
@@ -1,40 +1,173 @@
-- 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.) */




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


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

SELECT
customer_id,
market_date,
dense_rank() 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. */

SELECT
customer_id,
market_date,
row_number() OVER (PARTITION BY customer_id ORDER BY market_date DESC) AS visit_number
FROM
customer_purchases;


SELECT customer_id, market_date, visit_number
FROM
(
SELECT
customer_id,
market_date,
row_number() OVER (PARTITION BY customer_id ORDER BY market_date DESC) AS visit_number
FROM
customer_purchases

) AS recent_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,
count(DISTINCT market_date) AS purchase_count
FROM
customer_purchases
GROUP BY
customer_id, product_id;

-- I tried the code below, but I am getting error that DISTICT is not supported for window function.
/*SELECT
customer_id,
product_id,
COUNT(DISTINCT market_date) 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,
CASE
WHEN instr(product_name, '-') = 0 THEN NULL
ELSE TRIM(SUBSTR(product_name, INSTR(product_name, '-') + 1))
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
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.

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 daily_sales 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
daily_sales
)
SELECT
market_date,
total_sales
FROM
ranked_sales
WHERE
sales_rank_desc = 1
UNION
SELECT
market_date,
total_sales
FROM
ranked_sales
WHERE
sales_rank_asc = 1;


Loading