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.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 34 additions & 5 deletions 02_activities/assignments/Assignment2.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@
* Open a private window in your browser. Copy and paste the link to your pull request into the address bar. Make sure you can see your pull request properly. This helps the technical facilitator and learning support staff review your submission easily.

Checklist:
- [ ] Create a branch called `assignment-two`.
- [ ] Ensure that the repository is public.
- [ ] Review [the PR description guidelines](https://github.com/UofT-DSI/onboarding/blob/main/onboarding_documents/submissions.md#guidelines-for-pull-request-descriptions) and adhere to them.
- [ ] Verify that the link is accessible in a private browser window.
- [X] Create a branch called `assignment-two`.
- [X] Ensure that the repository is public.
- [X] Review [the PR description guidelines](https://github.com/UofT-DSI/onboarding/blob/main/onboarding_documents/submissions.md#guidelines-for-pull-request-descriptions) and adhere to them.
- [X] Verify that the link is accessible in a private browser window.

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.

Expand Down Expand Up @@ -54,7 +54,36 @@ The store wants to keep customer addresses. Propose two architectures for the CU
**HINT:** search type 1 vs type 2 slowly changing dimensions.

```
Your answer...
My answer:

Type 1 - will overwrite changes. We will only see the most recent address for each customer.
Below is the suggested columns for that:
- customer_id
- customer_first_name
- customer_last_name
- unit
- street
- city
- province
- postal_code
- country


Type 2- will keep all records and timestamp every row, allowing you to access the most recent address on file, but also the historical addresses for any given customer.
Below is the suggested columns for that:
- customer_id
- customer_first_name
- customer_last_name
- unit
- street
- city
- province
- postal_code
- country
- date_updated
- most_recent_address (Y/N column)


```

***
Expand Down
78 changes: 62 additions & 16 deletions 02_activities/assignments/assignment1.sql
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,22 @@

--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,
/* 2. Write a query that displays all of the columns and 10 rows from the customer 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),
Expand All @@ -27,46 +28,89 @@ filtered by vendor IDs between 8 and 10 (inclusive) using either:
2. one condition using BETWEEN
*/
-- option 1

select *
,(quantity * cost_to_customer_per_qty) as price
from customer_purchases where vendor_id <=10 and vendor_id >=8;

-- 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
v.vendor_id
,v.vendor_name
,v.vendor_type
,v.vendor_owner_first_name
,v.vendor_owner_last_name
,vba.booth_number
,vba.market_date
from vendor v
inner join vendor_booth_assignments vba on v.vendor_id = vba.vendor_id
order by v.vendor_name, vba.market_date;

/* SECTION 3 */

-- 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(vendor_id)
from vendor_booth_assignments
group by 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 spend
from customer c
left join customer_purchases cp on c.customer_id = cp.customer_id
group by c.customer_id
having spend > 2000
order by c.customer_last_name, c.customer_first_name;



Expand All @@ -81,16 +125,18 @@ 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)
*/
create 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');
-- 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! */


--

/* 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.
Expand Down
119 changes: 111 additions & 8 deletions 02_activities/assignments/assignment2.sql
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,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
/* 1. Write a query that selects from the customer_purchases table and numbers each customer’s
Expand All @@ -32,18 +34,37 @@ 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 * from customer_purchases;

select distinct
customer_id
,market_date
,dense_rank()over(partition by customer_id ORDER BY market_date asc) as 'visit_number'
from customer_purchases;
--group by customer_id, market_date




/* 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 distinct
customer_id
,market_date
,dense_rank()over(partition by customer_id ORDER BY market_date desc) as 'visit_number'
from customer_purchases;
--group by customer_id, market_date;


/* 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(product_id) over(partition by customer_id, product_id order by market_date,transaction_time asc) as 'purchase_number'
from customer_purchases;

-- String manipulations
/* 1. Some product names in the product table have descriptions like "Jar" or "Organic".
Expand All @@ -57,24 +78,65 @@ 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
*
,trim(
case
when product_name like '%-%' then 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
*
,trim(
case
when product_name like '%-%' then substr(product_name, instr(product_name,'-')+1)
else null
end) as description
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;
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";
"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. */



drop table if exists temp.best_worst_selling_days;

create temp table temp.best_worst_selling_days as
select
q1.market_date
,q1.daily_sales
,dense_rank() over(order by q1.daily_sales desc) as best_selling_day
,dense_rank() over(order by q1.daily_sales asc) as worst_selling_day
from
(select
market_date
,sum(quantity * cost_to_customer_per_qty) as daily_sales
from customer_purchases
group by market_date) q1;

select
market_date
,daily_sales
,'best selling day' as description
from temp.best_worst_selling_days where best_selling_day = 1
union all
select
market_date
,daily_sales
,'worst selling day' as description
from temp.best_worst_selling_days where worst_selling_day = 1;



/* SECTION 3 */

Expand All @@ -90,25 +152,54 @@ How many customers are there (y).
Before your final group by you should have the product of those two queries (x*y). */


select
p.product_name
,v.vendor_name
,sum( 5* x.original_price) as sales_revenue
from
(select distinct
vi.product_id
,vi.vendor_id
,c.customer_id
,vi.original_price
from vendor_inventory vi
cross join customer c) x
left join vendor v on v.vendor_id = x.vendor_id
left join product p on p.product_id = x.product_id
group by p.product_name, v.vendor_name;



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

drop table if exists product_units;

create table product_units as
select *
,current_timestamp as snapshot_timestamp
from product where product_qty_type = 'unit';

/*2. Using `INSERT`, add a new row to the product_units table (with an updated timestamp).
This can be any product you desire (e.g. add another record for Apple Pie). */

--select * from product_units;

insert into product_units values
(10,'Eggs','1 dozen',6,'unit',current_timestamp);


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

delete from product_units where product_id = 10
and snapshot_timestamp = (select min(snapshot_timestamp) from product_units);



-- UPDATE
Expand All @@ -128,6 +219,18 @@ 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. */

alter table product_units
add current_quantity INT;


with updated_quantity as
(select *
,row_number()over(partition by product_id order by market_date desc) as market_date_rank
from vendor_inventory)
update product_units
set current_quantity = coalesce
((select uq.quantity
from updated_quantity uq
where uq.product_id = product_units.product_id and uq.market_date_rank = 1),0);


Loading