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 .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.DS_Store
.vscode/
.sqbpro
*.db-journal
4 changes: 3 additions & 1 deletion 02_activities/assignments/Assignment2.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ The store wants to keep customer addresses. Propose two architectures for the CU
**HINT:** search type 1 vs type 2 slowly changing dimensions.

```
Your answer...
Type 1 is the overwrite approach. Our table is the same CUSTOMER_ADDRESS table and we would update the columns AddressID, CustomerID, Street, City, State, and Zipcode with each change/update. We wil not preserve old addresses only the most recent (MAX) one will be kept

Type 2 will retain changes through adding a new row to track the historical data. We would add rows to the type 1 approach, thus having a table that includes the following fields: AddressID, CustomerID, Street, City, State, and Zipcode with the addition of EffectiveDate and CurrentFlag, underscoring when the update was last current and whether or not it is current now. This allows us to retain the old, historical address data while leveraging the current, most up to date address information in the same table.
```

***
Expand Down
107 changes: 99 additions & 8 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') || ')'
AS details
FROM product;


--Windowed Functions
Expand All @@ -32,18 +37,33 @@ 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 *, ROW_NUMBER()
OVER (PARTITION BY customer_id ORDER BY market_date)
AS visit_number
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 recent_visit AS (SELECT *,
ROW_NUMBER()
OVER (PARTITION BY customer_id ORDER BY market_date DESC)
AS ranked
FROM customer_purchases
)
SELECT *
FROM recent_visit
WHERE ranked = 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 time_purchase
FROM customer_purchases;

-- String manipulations
/* 1. Some product names in the product table have descriptions like "Jar" or "Organic".
Expand All @@ -57,11 +77,26 @@ 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 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 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 @@ -73,6 +108,25 @@ 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_sales AS (
SELECT market_date, SUM(quantity * cost_to_customer_per_qty) AS total_sales
FROM customer_purchases
GROUP BY market_date),
ranked_sales AS (
SELECT market_date, total_sales,
RANK() OVER (ORDER BY total_sales ASC) AS rank_low,
RANK() OVER (ORDER BY total_sales DESC) AS rank_high
FROM daily_sales
)
SELECT market_date, total_sales,'worst' AS day_type
FROM ranked_sales
WHERE rank_low = 1

UNION

SELECT market_date, total_sales,'best' AS day_type
FROM ranked_sales
WHERE rank_high = 1;



Expand All @@ -89,27 +143,56 @@ 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 vendor_products AS (
SELECT vi.vendor_id, vi.product_id, vi.original_price
FROM vendor_inventory AS vi),

joined AS (
SELECT vp.vendor_id, vp.product_id, vp.original_price, c.customer_id
FROM vendor_products AS vp
CROSS JOIN customer AS c)

SELECT v.vendor_name, p.product_name, SUM(5 * e.original_price) AS money_made
FROM joined AS e
JOIN vendor AS v ON v.vendor_id = e.vendor_id
JOIN product AS p ON p.product_id = e.product_id
GROUP BY v.vendor_name, p.product_name
ORDER 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`. */


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 (7, 'Apple Pie', '12"', 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.*/


DELETE FROM product_units
WHERE product_id = 7
AND snapshot_timestamp <>
(SELECT MAX(snapshot_timestamp)
FROM product_units
WHERE product_id = 7);

-- UPDATE
/* 1.We want to add the current_quantity to the product_units table.
Expand All @@ -128,6 +211,14 @@ 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 = COALESCE(
(SELECT vi.quantity
FROM vendor_inventory AS vi
WHERE vi.product_id = product_units.product_id
ORDER BY vi.market_date DESC
LIMIT 1),0);

Binary file added 02_activities/assignments/assignment2_prompt1.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/assignments/assignment2_prompt2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
48 changes: 48 additions & 0 deletions 04_this_cohort/live_code/module_4/string_manipulations.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
-- string manipulations

SELECT DISTINCT

LTRIM(' THOMAS ROSENTHAL ') as [ltrim]
,RTRIM(' THOMAS ROSENTHAL ') as [rtrim]
,TRIM(' THOMAS ROSENTHAL ') as [trimmed]
,LTRIM(RTRIM(' THOMAS ROSENTHAL ')) as [both]

--replace
,REPLACE('THOMAS ROSENTHAL', ' ', ' WILLIAM ' ) -- add my middle name between first name and last name
,REPLACE('THOMAS ROSENTHAL', 'a','') -- case sensitive
,REPLACE('THOMAS ROSENTHAL', 'A','') -- replaces both A's
,REPLACE(REPLACE(customer_first_name, 'a',''),'e','') as new_customer_first_name

,UPPER(customer_first_name) as [upper]
,LOWER(customer_first_name) as [lower]

--concat
,customer_first_name || ' ' || customer_last_name as customer_name
,UPPER(customer_first_name) || ' ' || UPPER(customer_last_name) || ' ' || customer_postal_code as upper_cust_name


FROM customer;

SELECT DISTINCT
customer_last_name
,SUBSTR(customer_last_name,4) -- any length from the 4th character
,substr(customer_last_name,4,2)
,substr(customer_last_name, -5,4) -- counting from the right
,substr(customer_last_name,1,2) -- results with 2 characters
,substr(customer_last_name,0,2) -- results with 1 character instead of 2

--length
,length(customer_last_name)


,'THOMAS

ROSENTHAL'

,replace('THOMAS

ROSENTHAL', char(10), ' ' ) -- removing all instances of the line break from the string

FROM customer

WHERE customer_last_name REGEXP '(a)$' -- filtering to only end in a
15 changes: 15 additions & 0 deletions 04_this_cohort/live_code/module_5/CROSS_JOIN.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
--CROSS JOIN

DROP TABLE IF EXISTS temp.sizes;
CREATE TEMP TABLE IF NOT EXISTS temp.sizes (size TEXT);

INSERT INTO temp.sizes
VALUES('small'),
('medium'),
('large');

SELECT * FROM temp.sizes;

SELECT product_name, size
FROM product
CROSS JOIN temp.sizes
21 changes: 21 additions & 0 deletions 04_this_cohort/live_code/module_5/FIRST_VIEW.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- VIEW

-- vendor daily sales
DROP VIEW IF EXISTS vendor_daily_sales;
CREATE VIEW IF NOT EXISTS vendor_daily_sales AS

SELECT
md.market_date
,market_day
,market_year
,vendor_name
,SUM(quantity*cost_to_customer_per_qty) as sales


FROM market_date_info md
INNER JOIN customer_purchases cp
ON md.market_date = cp.market_date
INNER JOIN vendor v
ON v.vendor_id = cp.vendor_id

GROUP BY cp.market_date, v.vendor_id
21 changes: 21 additions & 0 deletions 04_this_cohort/live_code/module_5/INSERT_UPDATE_DELETE.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
--INSERT UPDATE AND DELETE

DROP TABLE IF EXISTS temp.product_expanded;
CREATE TEMP TABLE product_expanded AS
SELECT * FROM product;

INSERT INTO product_expanded
VALUES(26, 'Almonds', '1 lb',1, 'lbs');

--update our new record product_size to 1/2 kg
UPDATE product_expanded
--SELECT * FROM product_expanded
SET product_size = '1/2 kg', product_qty_type = 'kg'
WHERE product_id = 26;

-- delete our almonds
DELETE FROM product_expanded
--SELECT * FROM product_expanded
WHERE product_id = 26;

SELECT * from product_expanded
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
UPDATE new_customer_purchases
SET market_date = DATE('now')

INSERT INTO market_date_info
VALUES('2025-04-23','Wednesday','17','2025','8:00 AM','2:00 PM', 'nothing interesting','Spring', '20','28',0,0);
40 changes: 40 additions & 0 deletions 04_this_cohort/live_code/module_5/LIVE_DYNAMIC_VIEW.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
--VIEW
-- THIS ONLY WORKS IF YOU HAVE THE PROPER STEPS
-- IMPORT as csv
-- ?? update the market date info table to also have todays date!
-- UPDATING THE NEW DATA TO "TODAY" in the where statement


DROP VIEW IF EXISTS vendor_daily_sales;
CREATE VIEW IF NOT EXISTS vendor_daily_sales AS

SELECT
md.market_date
,market_day
,market_year
,vendor_name
,SUM(quantity*cost_to_customer_per_qty) as sales

-- want to update the VIEW
-- need to bring in the new data
-- new data is called new_customer_purchases
--but we want the old data too!
--....use a union to combine old and new

FROM market_date_info md

INNER JOIN (
SELECT * FROM
customer_purchases
UNION
SELECT * FROM
new_customer_purchases ) as cp
ON md.market_date = cp.market_date
INNER JOIN vendor v
ON v.vendor_id = cp.vendor_id

-- we want TODAYS data only
WHERE md.market_date = date('now')

GROUP BY cp.market_date, v.vendor_id

22 changes: 22 additions & 0 deletions 04_this_cohort/live_code/module_5/SELF_JOIN.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
-- SELF JOIN
drop table if exists temp.employees;
create temp table temp.employees
(
emp_id int,
emp_name text,
mgr_id int
);

insert into temp.employees
Values(1,'Thomas',3)
,(2,'Laura',4)
,(3,'Rohan',null)
,(4,'Jennie',3);


SELECT * FROM temp.employees

select a.emp_name,b.emp_name as mgr_name
from temp.employees a
left join temp.employees b
on a.mgr_id = b.emp_id
12 changes: 12 additions & 0 deletions 04_this_cohort/live_code/module_5/VIEW_IN_ANOTHER_QUERY.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- using a view in another query
SELECT
market_year
,market_week
,vendor_name
,SUM(sales) as weekly_sales

FROM vendor_daily_sales

GROUP BY market_year
,market_week
,vendor_name
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading