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 added 02_activities/assignment-one-diagram.png
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/assignment_two_edr.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
95 changes: 87 additions & 8 deletions 02_activities/assignments/assignment1.sql
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,28 @@

--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 = 7 or product_id = 9;

-- option 2
select * from customer_purchases
where product_id = 7;

select * from customer_purchases
where 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,30 +34,57 @@ 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 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_name, vba.market_date from vendor_booth_assignments vba
join vendor v on v.vendor_id = vba.vendor_id
order by v.vendor_name, vba.market_date



Expand All @@ -59,6 +93,11 @@ vendor_id field they both have in common, and sorts the result by vendor_name, t
-- 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
*,
count(*) as booth_rental_count
from vendor_booth_assignments
group by vendor_id



Expand All @@ -67,6 +106,16 @@ sticker to everyone who has ever spent more than $2000 at the market. Write a qu
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 total
from customer_purchases cp
join customer c on c.customer_id = cp.customer_id
group by c.customer_id, c.customer_last_name, c.customer_first_name
having SUM(cp.quantity * cp.cost_to_customer_per_qty) > 2000
order by c.customer_last_name, c.customer_first_name



Expand All @@ -81,6 +130,23 @@ 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 copy_vendor as
select * from vendor;

insert into copy_vendor (
vendor_id,
vendor_name,
vendor_type,
vendor_owner_first_name,
vendor_owner_last_name
)
values (
10,
'Thomass Superfood Store',
'Fresh Focused store',
'Thomas',
'Rosenthal'
);



Expand All @@ -89,6 +155,11 @@ VALUES(col1,col2,col3,col4,col5)

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 @@ -98,3 +169,11 @@ 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 total_spent
from customer_purchases
where strftime('%m', market_date) = '04' and strftime('%Y', market_date) = '2022'
group by customer_id
141 changes: 138 additions & 3 deletions 02_activities/assignments/assignment2.sql
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ 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, '') -- blank if NULL
|| ' ('
|| COALESCE(product_qty_type, 'unit') -- 'unit' if NULL
|| ')' AS product_description
FROM product;


--Windowed Functions
Expand All @@ -31,18 +39,55 @@ 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
customer_id,
market_date,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY market_date
) AS visit_num
FROM customer_purchases;

SELECT
customer_id,
market_date,
DENSE_RANK() OVER (
PARTITION BY customer_id
ORDER BY market_date
) AS visit_num
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. */

WITH ranked_visits AS (
SELECT
customer_id,
market_date,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY market_date DESC
) AS rev_visit_num
FROM customer_purchases
)
SELECT *
FROM ranked_visits
WHERE rev_visit_num = 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
customer_id,
product_id,
quantity,
COUNT(*) OVER (
PARTITION BY customer_id, product_id
) AS times_purchased
FROM customer_purchases;


-- String manipulations
Expand All @@ -56,11 +101,28 @@ Remove any trailing or leading whitespaces. Don't just use a case statement for
| 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,
CASE
WHEN INSTR(product_name, '-') > 0 THEN
TRIM(
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 *
FROM product
WHERE product_size REGEXP '[0-9]';


-- UNION
Expand All @@ -73,7 +135,28 @@ 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. */


WITH daily_totals AS (
SELECT
market_date,
SUM(quantity * cost_to_customer_per_qty) AS total_sales
FROM customer_purchases
GROUP BY market_date
),
ranked AS (
SELECT
market_date,
total_sales,
RANK() OVER (ORDER BY total_sales DESC) AS rank_high,
RANK() OVER (ORDER BY total_sales ASC) AS rank_low
FROM daily_totals
)
SELECT market_date, total_sales
FROM ranked
WHERE rank_high = 1
UNION
SELECT market_date, total_sales
FROM ranked
WHERE rank_low = 1;


/* SECTION 3 */
Expand All @@ -88,6 +171,19 @@ 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,
SUM(5 * vi.original_price) AS potential_revenue
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 customer c
GROUP BY
v.vendor_name,
p.product_name;



Expand All @@ -97,6 +193,26 @@ 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
p.*,
CURRENT_TIMESTAMP AS snapshot_timestamp
FROM product p
WHERE p.product_qty_type = 'unit';

INSERT INTO product_units (
product_id,
product_name,
product_size,
product_qty_type,
snapshot_timestamp
) VALUES (
9898,
'New Pie',
'Large',
'unit',
CURRENT_TIMESTAMP
);


/*2. Using `INSERT`, add a new row to the product_units table (with an updated timestamp).
Expand All @@ -108,7 +224,13 @@ This can be any product you desire (e.g. add another record for Apple Pie). */
/* 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 = 9898
AND snapshot_timestamp < (
SELECT MAX(snapshot_timestamp)
FROM product_units
WHERE product_id = 9898
);


-- UPDATE
Expand All @@ -129,5 +251,18 @@ Finally, make sure you have a WHERE statement to update the right row,
When you have all of these components, you can run the update statement. */


-- add column
ALTER TABLE product_units
ADD COLUMN current_quantity INT;

-- populate from most recent vendor_inventory quantity, defaulting NULL→0
UPDATE product_units pu
SET current_quantity = COALESCE((
SELECT vi.quantity
FROM vendor_inventory vi
WHERE vi.product_id = pu.product_id
ORDER BY vi.inventory_date DESC
LIMIT 1
), 0);


Binary file modified 05_src/sql/farmersmarket.db
Binary file not shown.