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
4 changes: 3 additions & 1 deletion 02_activities/assignments/Assignment2.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ The store wants to keep customer addresses. Propose two architectures for the CU

```
Your answer...
```

For type 1, it will overrite. Only the latest address is kept.
For type 2, there will be start_date and end_date column to keep track the history of address.

***

Expand Down
Binary file added 02_activities/assignments/SQL Assignment 1.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added 02_activities/assignments/SQL Assignment 2.pdf
Binary file not shown.
60 changes: 47 additions & 13 deletions 02_activities/assignments/assignment1.sql
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,29 @@

--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 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),
Expand All @@ -27,39 +35,50 @@ 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 >= 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 LOWER(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;


/* 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(*)
FROM vendor_booth_assignments
GROUP BY vendor_id;


/* 2. The Farmer’s Market Customer Appreciation Committee wants to give a bumper
Expand All @@ -68,7 +87,12 @@ 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_last_name, c.customer_first_name, SUM(quantity * cost_to_customer_per_qty) AS spending
FROM customer c
INNER JOIN customer_purchases cp ON c.customer_id = cp.customer_id
GROUP BY c.customer_last_name, c.customer_first_name
HAVING spending > 2000
ORDER BY c.customer_last_name, c.customer_first_name;

--Temp Table
/* 1. Insert the original vendor table into a temp.new_vendor and then add a 10th vendor:
Expand All @@ -81,14 +105,21 @@ 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! */
SELECT customer_id, strftime('%m', market_date) AS month, strftime('%Y', market_date) AS year
FROM customer_purchases;



Expand All @@ -97,4 +128,7 @@ 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 spending
FROM customer_purchases
WHERE year = '2022' AND month = '04'
GROUP BY customer_id, month, year;
94 changes: 86 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
COALESCE(IFNULL(product_name || ', ' || product_size|| ' (' || 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 @@ -33,16 +35,32 @@ each new market date for each customer, or select only the unique market dates p
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) as number_of_visit
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 *
FROM(
SELECT DISTINCT customer_id,
market_date,
dense_rank() OVER(PARTITION BY customer_id ORDER BY market_date DESC) as number_of_visit
FROM customer_purchases
)x
WHERE number_of_visit = 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 DISTINCT customer_id,
product_id,
COUNT(*) OVER(PARTITION BY customer_id, product_id) AS number_of_purchases
FROM customer_purchases;


-- String manipulations
Expand All @@ -58,9 +76,17 @@ 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 product_name,
CASE WHEN INSTR(product_name, '-') = 0 THEN NULL
ELSE TRIM(SUBSTR(product_name, INSTR(product_name, '-')+1, Length(product_name)-INSTR(product_name, '-'))) END 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
Expand All @@ -73,9 +99,21 @@ HINT: There are a possibly a few ways to do this query, but if you're struggling
3) Query the second temp table twice, once for the best day, once for the worst day,
with a UNION binding them. */




DROP VIEW IF EXISTS total_sales_per_date;
CREATE VIEW IF NOT EXISTS total_sales_per_date AS
SELECT DISTINCT market_date,
SUM(quantity*cost_to_customer_per_qty) total_sales
FROM customer_purchases
GROUP BY market_date;

SELECT market_date, MAX(total_sales) sales
FROM total_sales_per_date
UNION
SELECT market_date, MIN(total_sales) sales
FROM total_sales_per_date
;


/* SECTION 3 */

-- Cross Join
Expand All @@ -89,27 +127,49 @@ Think a bit about the row counts: how many distinct vendors, product names are t
How many customers are there (y).
Before your final group by you should have the product of those two queries (x*y). */


SELECT v.vendor_name,
p.product_name,
SUM(original_price*5) as total_sales
FROM(
SELECT *
FROM(
SELECT DISTINCT vendor_id, product_id, original_price
FROM vendor_inventory) vendor_product
CROSS JOIN customer
)x
INNER JOIN vendor v ON v.vendor_id = x.vendor_id
INNER JOIN product p ON p.product_id = x.product_id
GROUP BY v.vendor_name, p.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 IF NOT EXISTS product_units AS
SELECT *, DATETIME('now') as current_timestamp
FROM product
WHERE product_qty_type = 'unit';

SELECT * from product_units
order by product_id;

/*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(product_id, product_name, product_size, product_category_id, product_qty_type, current_timestamp)
VALUES(24, 'Applie Pie','Medium',2,'unit',DATETIME('now'));


-- 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 =24;

-- UPDATE
/* 1.We want to add the current_quantity to the product_units table.
Expand All @@ -128,6 +188,24 @@ 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;


UPDATE product_units
SET current_quantity = x.current_quantity
FROM (
SELECT p.product_id,
COALESCE(temp.quantity,0) current_quantity
FROM product p
LEFT JOIN (
SELECT * FROM(
SELECT DISTINCT product_id,
quantity,
market_date,
dense_rank()OVER(PARTITION BY product_id ORDER BY market_date DESC) as rank
from vendor_inventory)
WHERE rank = 1) temp ON p.product_id = temp.product_id) x
WHERE x.product_id = product_units.product_id;