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
2 changes: 2 additions & 0 deletions 03_homework/homework_1.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
Homework is attached to pull request.

# Homework 1: farmersmarket.db

- Due on Thursday, May 16 at 11:59pm
Expand Down
37 changes: 29 additions & 8 deletions 03_homework/homework_2.sql
Original file line number Diff line number Diff line change
@@ -1,42 +1,63 @@
--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

/*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 BETWEEN 8 AND 10;

-- option 2

--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 vendor_name, market_date;
34 changes: 30 additions & 4 deletions 03_homework/homework_3.sql
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
-- 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(booth_number) AS booth_rentals
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.*
,sum(quantity*cost_to_customer_per_qty) AS expenditure
FROM customer AS c
INNER JOIN customer_purchases AS cp
ON c.customer_id = cp.customer_id
GROUP BY cp.customer_id
HAVING expenditure > 2000
ORDER BY customer_last_name, customer_first_name;


--Temp Table
Expand All @@ -23,18 +33,34 @@ 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 TEMP TABLE new_vendor AS
SELECT * FROM vendor;
INSERT INTO new_vendor
VALUES(10, 'Thomass Superfood Store', 'Fresh Focused', '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
,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
,strftime('%m', market_date) AS month
,strftime('%Y', market_date) AS year
,sum(quantity*cost_to_customer_per_qty) AS expenditure
FROM customer_purchases
WHERE month = '04' AND year = '2019'
GROUP BY customer_id, month, year;
71 changes: 69 additions & 2 deletions 03_homework/homework_4.sql
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ HINT: keep the syntax the same, but edited the correct components with the strin
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 product_list
FROM product;


--Windowed Functions
Expand All @@ -29,12 +31,77 @@ You can either display all rows in the customer_purchases table, with the counte
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 DISTINCT customer_id, market_date
,dense_rank()OVER(PARTITION BY customer_id ORDER BY market_date ASC) 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
FROM(
SELECT DISTINCT customer_id, market_date
,dense_rank()OVER(PARTITION BY customer_id ORDER BY market_date DESC) AS visit_number
FROM customer_purchases
) AS x
WHERE x.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 *
,count()OVER(PARTITION BY product_id,customer_id ORDER BY market_date,transaction_time ASC)
AS rolling_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
,rtrim(ltrim(substr(product_name,nullif(instr(product_name,'-')+1,1)))) 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.

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. */
DROP TABLE IF EXISTS sales_table;
CREATE TEMP TABLE sales_table AS
SELECT market_date
,sum(quantity*cost_to_customer_per_qty) AS sales
FROM customer_purchases
GROUP BY market_date;
DROP TABLE IF EXISTS ranked_table;
CREATE TEMP TABLE ranked_table AS
SELECT *
,rank()OVER(ORDER BY sales DESC) AS best
,rank()OVER(ORDER BY sales ASC) AS worst
FROM sales_table;
SELECT market_date,sales
FROM ranked_table
WHERE best = 1
UNION
SELECT market_date,sales
FROM ranked_table
WHERE worst = 1;
80 changes: 44 additions & 36 deletions 03_homework/homework_5.sql
Original file line number Diff line number Diff line change
@@ -1,33 +1,3 @@
-- 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. */



/* 2. Filter the query to show any product_size value that contain a number with REGEXP. */



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



-- Cross Join
/*1. Suppose every vendor in the `vendor_inventory` table had 5 of each of their products to sell to **every**
customer on record. How much money would each vendor make per product?
Expand All @@ -38,27 +8,49 @@ Remember, CROSS JOIN will explode your table rows, so CROSS JOIN should likely b
Think a bit about the row counts: how many distinct vendors, product names are there (x)?
How many customers are there (y).
Before your final group by you should have the product of those two queries (x*y). */

SELECT vendor_name, product_name
,sum(5*original_price) AS sales
FROM(
SELECT DISTINCT v.vendor_name, p.product_name, vi.original_price, c.customer_id
FROM vendor_inventory AS vi
INNER JOIN vendor AS v
ON vi.vendor_id = v.vendor_id
INNER JOIN product AS p
ON vi.product_id = p.product_id
CROSS JOIN customer AS c
) AS x
GROUP BY vendor_name,product_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). */

INSERT INTO product_units
VALUES(7,'Apple Pie','10"',3,'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,snapshot_timestamp) IN(
SELECT pu1.product_id, pu1.snapshot_timestamp
FROM product_units AS pu1
INNER JOIN product_units AS pu2
ON pu1.product_id = pu2.product_id
WHERE pu1.snapshot_timestamp < pu2.snapshot_timestamp);


-- UPDATE
Expand All @@ -77,5 +69,21 @@ Third, SET current_quantity = (...your select statement...), remembering that WH
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. */


DROP TABLE IF EXISTS product_quantity;
CREATE TEMP TABLE product_quantity AS
SELECT product_id
,coalesce(quantity, 0) AS last_quantity
FROM(
SELECT p.product_id, vi.quantity
,rank()OVER(PARTITION BY vi.product_id ORDER BY vi.market_date DESC) AS last
FROM product AS p
LEFT JOIN vendor_inventory AS vi
ON p.product_id = vi.product_id
) as x
WHERE last = 1
ORDER BY product_id;
ALTER TABLE product_units
ADD current_quantity INT;
UPDATE product_units
SET current_quantity = (SELECT last_quantity FROM product_quantity
WHERE product_units.product_id = product_quantity.product_id);
10 changes: 10 additions & 0 deletions 03_homework/homework_6.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,13 @@
<br>

**Write**: Reflect on your previous work and how you would adjust to include ethics and inequity components. Total length should be a few paragraphs, no more than one page.

I am a junior engineer in training and a candidate to become a professional engineer within the next few months. The code of ethics of engineers represents all the duties and obligations that govern the conduct of members of this profession such as myself. Its primary objective is the protection of the public, but it also aims to preserve the honor of the profession.

All engineers must comply with a set of ethical obligations that aim to protect the public and preserve the honor and dignity of the profession. The duties and obligations can be broadly divided into four categories. They include those towards the public, those towards clients, those towards the profession, and those relative to self-promotion.

Starting with an engineer’s obligations towards the public, they must be conscious of the consequences of their work on people and the environment in all aspects of their work. An engineer must speak up when they deem that certain engineering work poses a danger to public safety. Also, their opinions on engineering matters should only be given based on sufficient knowledge.

Moving on to the duties towards clients, an engineer must carry out their professional work with integrity and with no false representation of their level of competence. An engineer must also exhibit reasonable availability and diligence in their professional practice. Another important aspect is the proper use of their seal and signature which is governed by specific regulations. An engineer should also remain professionally independent and impartial while avoiding conflicts of interest. In addition, the secrecy of confidential information should always be respected.

As for their obligations towards the engineering profession, an engineer must refrain from acts that are derogatory to the dignity of the profession. Also, they must maintain a professional relation with the order of which they are a member as well as their colleagues. In addition, an engineer must contribute to the advancement and development of the profession by sharing their knowledge and experience with colleagues or students. Finally, with regards to obligations relative to self-promotion, they must not make false claims about their services such as misleading the public about their experience or qualifications.