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
Binary file not shown.
Binary file not shown.
65 changes: 57 additions & 8 deletions 02_activities/assignments/assignment1.sql
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,25 @@
/* 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 c WHERE c.product_id IN (4,9);

-- option 2


SELECT * FROM customer_purchases c WHERE c.product_id = 4 OR c.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:
Expand All @@ -28,30 +33,48 @@ filtered by vendor IDs between 8 and 10 (inclusive) using either:
*/
-- 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 v.vendor_id, v.vendor_name, v.vendor_type, v.vendor_owner_first_name, v.vendor_owner_last_name, vb.booth_number, vb.market_date
FROM vendor v
INNER JOIN vendor_booth_assignments vb
ON v.vendor_id = vb.vendor_id
ORDER BY v.vendor_name, vb.market_date;


/* SECTION 3 */
Expand All @@ -60,14 +83,21 @@ vendor_id field they both have in common, and sorts the result by vendor_name, t
/* 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 count 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 spent
FROM customer AS c
JOIN customer_purchases AS cp ON cp.customer_id = c.customer_id
GROUP BY c.customer_id, c.customer_first_name, c.customer_last_name
HAVING SUM(cp.quantity * cp.cost_to_customer_per_qty) > 2000
ORDER BY c.customer_last_name, c.customer_first_name;



--Temp Table
Expand All @@ -82,19 +112,38 @@ When inserting the new vendor, you need to appropriately align the columns to be
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;

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

HINTS: you will need to AGGREGATE, GROUP BY, and filter...
but remember, STRFTIME returns a STRING for your WHERE statement!! */

SELECT customer_id, SUM(quantity * cost_to_customer_per_qty) AS total_spent
FROM customer_purchases
WHERE strftime('%m', market_date) = '04'
AND strftime('%Y', market_date) = '2022'
GROUP BY customer_id;
134 changes: 127 additions & 7 deletions 02_activities/assignments/assignment2.sql
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ 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
Expand All @@ -32,18 +37,48 @@ 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(). */

/*Approach using ROW_NUMBER() */
SELECT
customer_id,
market_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date) AS visit_number
FROM customer_purchases;

/*Approach using DENSE_RANK() selecting distinct market dates */
SELECT
customer_id,
market_date,
DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY market_date) AS visit_number
FROM ( SELECT DISTINCT customer_id, market_date FROM customer_purchases ) visits;

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

/*Reversing the result to 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;


/*Using Temporary table */

DROP TABLE IF EXISTS temp.customer_visits;
CREATE TEMP TABLE IF NOT EXISTS temp.customer_visits AS
SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date DESC) AS visit_number
FROM customer_purchases;

SELECT * FROM temp.customer_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 *, COUNT(*) OVER (PARTITION BY customer_id, product_id) AS count_cstmr_prod_purchase FROM customer_purchases;


-- String manipulations
/* 1. Some product names in the product table have descriptions like "Jar" or "Organic".
Expand All @@ -57,10 +92,23 @@ 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 p.*, p.product_name,
TRIM(CASE
WHEN INSTR(p.product_name, '-') > 0
THEN SUBSTR(p.product_name, INSTR(p.product_name, '-') + 1)
ELSE NULL
END) AS description
FROM product p;

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

SELECT p.*, p.product_name,
TRIM(CASE
WHEN INSTR(p.product_name, '-') > 0
THEN SUBSTR(p.product_name, INSTR(p.product_name, '-') + 1)
ELSE NULL
END) AS description
FROM product p
WHERE p.product_size REGEXP '[0-9]';


-- UNION
Expand All @@ -74,8 +122,35 @@ HINT: There are a possibly a few ways to do this query, but if you're struggling
with a UNION binding them. */


DROP TABLE IF EXISTS temp.date_sales;
DROP TABLE IF EXISTS temp.date_sales_ranked;

CREATE TEMP TABLE IF NOT EXISTS temp.date_sales AS
SELECT
market_date,
SUM(quantity * cost_to_customer_per_qty) AS total_sales
FROM customer_purchases
GROUP BY market_date;

CREATE TEMP TABLE IF NOT EXISTS temp.date_sales_ranked AS
SELECT
market_date,
total_sales,
DENSE_RANK() OVER (ORDER BY total_sales DESC) AS best_day_rank,
DENSE_RANK() OVER (ORDER BY total_sales ASC) AS worst_day_rank
FROM date_sales;


SELECT market_date, total_sales, 'Best Day' AS day
FROM temp.date_sales_ranked
WHERE best_day_rank = 1

UNION

SELECT market_date, total_sales, 'Worst Day' AS day
FROM temp.date_sales_ranked
WHERE worst_day_rank = 1;

/* SECTION 3 */

-- Cross Join
Expand All @@ -88,7 +163,15 @@ 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
v.vendor_name,
p.product_name,
(customer_count * vi.original_price * 5) AS potential_sales_per_product
FROM vendor_inventory vi
JOIN vendor v ON vi.vendor_id = v.vendor_id
JOIN product p ON vi.product_id = p.product_id
CROSS JOIN (SELECT COUNT(*) AS customer_count FROM customer)
GROUP BY v.vendor_name, p.product_name, vi.original_price;


-- INSERT
Expand All @@ -97,18 +180,22 @@ 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`. */


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 (product_id, product_name, product_size, product_category_id, product_qty_type, snapshot_timestamp) VALUES (100, 'Mango Pie', 'Large', 1, '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 = 100 AND product_name = 'Mango Pie';


-- UPDATE
Expand All @@ -128,6 +215,39 @@ 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;


/*Determining last single quantity with a sum() per product and coalesce */
SELECT *, COALESCE(
(SELECT SUM(vi.quantity)
FROM vendor_inventory vi
WHERE vi.product_id = pu.product_id
AND vi.market_date =
(SELECT MAX(vi2.market_date)
FROM vendor_inventory vi2
WHERE vi2.product_id = pu.product_id
)
),
0)
FROM product_units pu
WHERE pu.product_qty_type = 'unit';


/*UPDATE statement with WHERE clause */

UPDATE product_units AS pu
SET current_quantity =
COALESCE(
(SELECT SUM(vi.quantity)
FROM vendor_inventory vi
WHERE vi.product_id = pu.product_id
AND vi.market_date =
(SELECT MAX(vi2.market_date)
FROM vendor_inventory vi2
WHERE vi2.product_id = pu.product_id
)
),
0)
WHERE pu.product_qty_type = 'unit';