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
32 changes: 30 additions & 2 deletions 03_homework/homework_2.sql
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
--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 ASC 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

Expand All @@ -22,21 +26,45 @@ 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_category_id, product_name,
CASE WHEN product_qty_type = "unit" THEN "unit"
ELSE "bulk" END AS product_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_category_id, product_name,
CASE WHEN product_qty_type = "unit" THEN "unit"
ELSE "bulk" END AS product_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
INNER JOIN vendor_booth_assignments
ON vendor.vendor_id = vendor_booth_assignments.vendor_id
ORDER BY vendor_name, market_date ASC
41 changes: 36 additions & 5 deletions 03_homework/homework_3.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,25 @@
/* 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
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
customer_first_name,
customer_last_name,
sum(quantity * cost_to_customer_per_qty) as customer_spent
FROM customer
JOIN customer_purchases ON customer.customer_id = customer_purchases.customer_id
GROUP BY customer_last_name, customer_first_name
HAVING customer_spent > 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:
Expand All @@ -23,18 +33,39 @@ 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 temp_new_vendor;
CREATE TEMP 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,'Thomas Superfood Store','a Fresh Focused store', 'Thomas', 'Rosenthal');
select * from temp_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 customer_spent
FROM customer_purchases
WHERE month = '04' and year = '2019'
GROUP BY customer_id

53 changes: 53 additions & 0 deletions 03_homework/homework_4.sql
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ 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,'') || ')'
FROM product

SELECT
product_name || ', ' || coalesce(product_size,'unit')|| ' (' || coalesce(product_qty_type,'unit') || ')'
FROM product



Expand All @@ -30,11 +37,57 @@ 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
customer_id,
market_date,
visit
FROM
(
SELECT
customer_id,
market_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date ASC) AS 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
customer_id,
market_date,
visit
FROM
(
SELECT
customer_id,
market_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date DESC) AS visit
FROM
customer_purchases
)

SELECT
customer_id,
market_date,
visit
FROM
(
SELECT
customer_id,
market_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date DESC) AS visit
FROM
customer_purchases
) as x
where x.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 product_id, customer_id) as Amount
FROM customer_purchases

77 changes: 72 additions & 5 deletions 03_homework/homework_5.sql
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,28 @@ 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 (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
product_name,
product_size,
CASE
WHEN INSTR(product_name, '-') > 0 THEN TRIM(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.
Expand All @@ -26,6 +43,22 @@ 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 TABLE IF EXISTS sales_total;
CREATE TEMP TABLE sales_total AS

select product_id, market_date, quantity, cost_to_customer_per_qty, sum(quantity*cost_to_customer_per_qty) as sales
from customer_purchases
group by market_date;
select * from sales_total;

DROP TABLE IF EXISTS sales_highest_lowest;
CREATE TEMP TABLE sales_highest_lowest AS
select market_date, min(sales) as Sales, "Worst Day" as Day
from sales_total
union
SELECT market_date, max(sales) as Sales, "Best Day" as Day
from sales_total;
SELECT * from sales_highest_lowest


-- Cross Join
Expand All @@ -39,27 +72,53 @@ 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). */


WITH VendorProduct AS (
SELECT vend.vendor_id, vend.vendor_name, prod.product_id, prod.product_name
FROM vendor vend
CROSS JOIN product prod
)
SELECT
vend_prod.vendor_name,
vend_prod.product_name,
SUM(5 * vend_inven.original_price) AS total_revenue
FROM VendorProduct vend_prod
JOIN vendor_inventory vend_inven ON vend_prod.vendor_id = vend_inven.vendor_id AND vend_prod.product_id = vend_inven.product_id
GROUP BY vend_prod.vendor_name, vend_prod.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`. */

ROP TABLE IF EXISTS product_units;
CREATE TEMP TABLE product_units AS
SELECT
product_id,
product_name,
product_size,
product_category_id,
product_qty_type,
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 (12345, 'Apple 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_name like '%Apple Pie%'

-- UPDATE
/* 1.We want to add the current_quantity to the product_units table.
Expand All @@ -78,4 +137,12 @@ 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 = (
SELECT COALESCE(MAX(quantity), 0)
FROM vendor_inventory
WHERE vendor_inventory.product_id = product_units.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.

Reflecting on my learnings from the Knowledge Management courses at the Faculty of Information and my prior experience with data, I’ve come to understand the paramount importance of incorporating ethical and inequity considerations throughout the data lifecycle.
At the outset, during data collection, it’s crucial to respect privacy and consent norms, which not only upholds ethical standards but also enhances data accuracy. Following this, in the representation of data, it’s essential to ensure fair representation of diverse groups to avoid any biases or disparities.
Privacy is another key aspect, where access to data should be limited to only those who need it, thereby safeguarding sensitive information. When it comes to usage, it’s advisable to refrain from collecting unnecessary personal data and to maintain transparency about the data being collected and its intended use.
Moreover, conducting regular audits is an ongoing commitment that ensures compliance with ethical procedures and standards. These steps are just a few among many to ensure the integration of ethics and inequity components when working with data.
As we progress into an era where data accessibility is increasing and AI is advancing, these considerations become even more critical to ensure ethical and equitable data practices.