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
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)

![image](https://github.com/monzchan/SQL/assets/166637673/863d31cf-46f9-4d5e-85ff-a4a6128e3680)
33 changes: 32 additions & 1 deletion 03_homework/homework_2.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,49 @@

# 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 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.
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:
SELECT * FROM customer_purchases
WHERE product_id BETWEEN 4 AND 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
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 *,
CASE WHEN product_name LIKE '%pepper%' THEN 1 ELSE 0 END AS pepper_flag
FROM product



# 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`.
SELECT *
FROM vendor
JOIN vendor_booth_assignments
ON vendor.vendor_id=vendor_booth_assignments.vendor_id
ORDER BY vendor_name, market_date


34 changes: 34 additions & 0 deletions 03_homework/homework_3.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,53 @@

# 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)
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_first_name, c.customer_last_name, sum(cp.quantity* cp.cost_to_customer_per_qty) AS totalpurchase
FROM customer c
INNER JOIN customer_purchases cp
ON c.customer_id = cp.customer_id
GROUP BY customer_last_name, customer_first_name
HAVING totalpurchase>2000
ORDER BY customer_last_name, customer_first_name





# Temp Table
1. Insert the original vendor table into a temp.new_vendor and then add a 10th vendor: Thomass Superfood Store, a Fresh Focused store, owned by Thomas Rosenthal
**HINT**: This is two total queries -- first create the table from the original, then insert the new 10th vendor. When inserting the new vendor, you need to appropriately align the columns to be inserted (there are five columns to be inserted, I've given you the details, but not the syntax)

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 VALUES (10, 'Thomass Superfood', 'Fresh Focused', 'Rosenthal', 'Thomas');




# 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('%Y', market_date), STRFTIME('%m', market_date)
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('%Y', market_date) AS market_year, STRFTIME('%m', market_date) AS market_month
, SUM(quantity * cost_to_customer_per_qty) AS totalpurchase
FROM customer_purchases
GROUP BY market_year, market_month, customer_id
HAVING market_year LIKE '2019' AND market_month LIKE '04'
59 changes: 59 additions & 0 deletions 03_homework/homework_4.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,40 @@ Find the NULLs and then using COALESCE, replace the NULL with a blank for the fi

**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,
Max(x.visit) as total_visit
FROM(
SELECT customer_id,
DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY market_date)AS visit
FROM customer_purchases)x
GROUP BY customer_id

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 cp.*,
DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY market_date) AS visit_number
FROM customer_purchases AS cp

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 *
FROM
(select product_id, customer_id,
COUNT()OVER(PARTITION BY product_id ORDER BY customer_id ) AS no_of_times_of_purchases
from customer_purchases
ORDER BY customer_id)x
GROUP BY customer_id

# 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!
Expand All @@ -39,7 +63,42 @@ You can either display all rows in the customer_purchases table, with the counte

**HINT**: you might need to use INSTR(product_name,'-') to find the hyphens. INSTR will help split the column.

SELECT product_name,
CASE WHEN product_name LIKE '%-%' THEN
substr(product_name, INSTR(product_name, '-')+2)Else NULL
END as description
FROM product

# 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_per_market AS (
SELECT
market_date,
ROUND(SUM(quantity * cost_to_customer_per_qty),2) AS sales

FROM customer_purchases
GROUP BY market_date
)

,market_dates_ranked_by_sales AS (
SELECT
market_date,
sales,
RANK() OVER (ORDER BY sales) AS sales_rank_asc,
RANK() OVER (ORDER BY sales DESC) AS sales_rank_desc

FROM sales_per_market
)

SELECT market_date, sales, sales_rank_desc AS sales_rank
FROM market_dates_ranked_by_sales
WHERE sales_rank_asc = 1

UNION

SELECT market_date, sales, sales_rank_desc AS sales_rank
FROM market_dates_ranked_by_sales
WHERE sales_rank_desc = 1
51 changes: 50 additions & 1 deletion 03_homework/homework_5.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,41 @@

**HINT**: Be sure you select only relevant columns and rows. Remember, CROSS JOIN will explode your table rows, so CROSS JOIN should likely be a subquery. 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 DISTINCT vendor_name, product_name, cost_to_customer_per_qty,
cost_to_customer_per_qty *5 *28 AS total_sale
FROM vendor v
JOIN vendor_inventory vi
ON v. vendor_id = vi.vendor_id
JOIN product p
ON vi.product_id = p.product_id
JOIN customer_purchases cp
ON p.product_id = cp.product_id

# 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 temp.product_units;
CREATE TEMP 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 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(50,'Apple pie', '300lb', 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](https://imgflip.com/i/8iq872).

DELETE FROM product_units
WHERE product_id=50

# UPDATE
1. We want to add the current_quantity to the product_units table. First, add a new column, `current_quantity` to the table using the following syntax.
Expand All @@ -33,5 +56,31 @@ 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.

ALTER TABLE product_units
ADD current_quantity INT;


-----------------------------

DROP TABLE IF EXISTS temp.product_quantity;
CREATE TEMP TABLE product_quantity AS
SELECT product_id AS product_id,
COALESCE(quantity, 0) AS quantity
FROM
(SELECT p.product_id, m.quantity
FROM product AS p
LEFT JOIN
(SELECT x.product_id, x.quantity
FROM (
SELECT *,
RANK() OVER(PARTITION BY product_id ORDER BY market_date DESC) as current_transaction
FROM vendor_inventory)x
WHERE x.current_transaction=1) as m
ON p.product_id = m.product_id)


UPDATE product_units
SET current_quantity = (
SELECT quantity
FROM product_quantity
WHERE product_units.product_id = product_quantity.product_id
)
6 changes: 6 additions & 0 deletions 03_homework/homework_6.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,9 @@
<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 have been working in the hospital as a nurse for over 6 years and I have encounted quite a lot of ethical dilema.

For example, there was a patient approaching me to ask about the update on her lab report regrading a specimen sent at the date of operation. As a nurse working in the specialty clinic, I was able to access to all patient's information as long as the patient was an active out-patient at our clinic. However, I was not the nurse in charge of that patient and I was not involved in the operation that day, so it might not be ethical to retrieve data from a patient out of my scope of care. Therefore, I only explained to her about the situation and the ethical issues, and direct her to ask about information from her family doctor.

Another example would be my co-worker being admitted for an operation, and I was a nurse involved in the care that day. As a case nurse, I was authorized to retrieve patient's data about the patient's conditions such as her medical history, family backgrund, current medical conditions, and current medication etc, so as to provide patient-centered care. However, there was always an issue abut how much a nurse should know about that patient. As this patient was admitted for a minor procedure, namely the suturing of a laceration. Retrieving data about whether or not she has medication allergy, diabetic condition for wound healing should be enough to determine the care to be provided. Other data such as her family history, marital status, psychological consultation etc may not be significant. This example is brought up to stress on the importance of defining the boundary of data retrieval for the purpose of action.