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
10 changes: 6 additions & 4 deletions 02_activities/assignments/Cohort_8/assignment2.sql
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ SELECT
product_name || ', ' || product_size|| ' (' || product_qty_type || ')'
FROM product


But wait! The product table has some bad data (a few NULL values).
Find the NULLs and then using COALESCE, replace the NULL with a
blank for the first problem, and 'unit' for the second problem.
Find the NULLs and then using COALESCE, replace the NULL with a blank for the first column with
nulls, and 'unit' for the second column with nulls.

HINT: keep the syntax the same, but edited the correct components with the string.
**HINT**: keep the syntax the same, but edited the correct components with the string.
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.) */
All the other rows will remain the same. */




Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
115 changes: 100 additions & 15 deletions 02_activities/assignments/DC_Cohort/assignment2.sql
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,21 @@ SELECT
product_name || ', ' || product_size|| ' (' || product_qty_type || ')'
FROM product


But wait! The product table has some bad data (a few NULL values).
Find the NULLs and then using COALESCE, replace the NULL with a
blank for the first problem, and 'unit' for the second problem.
Find the NULLs and then using COALESCE, replace the NULL with a blank for the first column with
nulls, and 'unit' for the second column with nulls.

HINT: keep the syntax the same, but edited the correct components with the string.
**HINT**: keep the syntax the same, but edited the correct components with the string.
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.) */

All the other rows will remain the same. */

SELECT
product_name || ', ' ||
COALESCE(product_size || ' ', '') ||
'(' || COALESCE(product_qty_type, 'unit') || ')' AS product_description
FROM product;

--Windowed Functions
/* 1. Write a query that selects from the customer_purchases table and numbers each customer’s
Expand All @@ -32,18 +37,36 @@ 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,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date) AS visit_number
FROM customer_purchases
ORDER BY customer_id, market_date;

/* 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 visit_rank
FROM customer_purchases
)
SELECT customer_id, market_date
FROM ranked_visits
WHERE visit_rank = 1
ORDER BY customer_id;

/* 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 times_purchased_this_product
FROM customer_purchases
ORDER BY customer_id, product_id, market_date;

-- String manipulations
/* 1. Some product names in the product table have descriptions like "Jar" or "Organic".
Expand All @@ -57,11 +80,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,
NULLIF(TRIM(SUBSTR(product_name, INSTR(product_name, '-') + 1)), '') AS description
FROM product
WHERE INSTR(product_name, '-') > 0;

/* 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
/* 1. Using a UNION, write a query that displays the market dates with the highest and lowest total sales.
Expand All @@ -73,7 +102,32 @@ 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 AS (
SELECT
market_date,
total_sales,
RANK() OVER (ORDER BY total_sales DESC) AS best_rank,
RANK() OVER (ORDER BY total_sales ASC) AS worst_rank
FROM daily_sales
)
SELECT market_date, total_sales, 'Highest sales day' AS label
FROM ranked
WHERE best_rank = 1

UNION ALL

SELECT market_date, total_sales, 'Lowest sales day' AS label
FROM ranked
WHERE worst_rank = 1

ORDER BY total_sales DESC;


/* SECTION 3 */
Expand All @@ -89,27 +143,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,
5 * COUNT(DISTINCT c.customer_id) * vi.quantity * 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
ORDER BY potential_revenue DESC;

-- 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 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
SELECT *, CURRENT_TIMESTAMP
FROM product
WHERE product_name = 'Apple Pie';

-- 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 = 'Apple Pie'
AND snapshot_timestamp = (
SELECT MIN(snapshot_timestamp)
FROM product_units
WHERE product_name = 'Apple Pie'
);

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

UPDATE product_units
SET current_quantity = COALESCE((
SELECT quantity
FROM vendor_inventory vi
WHERE vi.product_id = product_units.product_id
ORDER BY market_date DESC, vendor_id
LIMIT 1
), 0);


28 changes: 15 additions & 13 deletions 03_instructional_team/sqbpro_originals/module_3.sqbpro
Original file line number Diff line number Diff line change
Expand Up @@ -105,19 +105,6 @@ Filter to number of purchases between 300 and 500 */

/* 2. What is the name of the vendor who sells pie */

</sql><sql name="CTE">/* MODULE 3 */
/* Common Table Expression (CTE) */


/* 1. Calculate sales per vendor per day */
SELECT





/* ... re-aggregate the daily sales for each WEEK instead now */

</sql><sql name="temp_table">/* MODULE 3 */
/* Temp Tables */

Expand All @@ -142,6 +129,21 @@ CREATE TABLE temp.new_vendor_inventory AS
/* 2. put the previous table into another temp table, e.g. as temp.new_new_vendor_inventory */


</sql><sql name="CTE">/* MODULE 3 */
/* Common Table Expression (CTE) */


/* 1. Calculate sales per vendor per day */
SELECT





/* ... re-aggregate the daily sales for each WEEK instead now */



</sql><sql name="dates">/* MODULE 3 */
/* Date functions */

Expand Down
44 changes: 22 additions & 22 deletions 03_instructional_team/sqbpro_originals/module_5.sqbpro
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?><sqlb_project><window><main_tabs open="structure browser pragmas query" current="3"/></window><tab_structure><column_width id="0" width="300"/><column_width id="1" width="0"/><column_width id="2" width="100"/><column_width id="3" width="12168"/><column_width id="4" width="0"/><expanded_item id="0" parent="1"/><expanded_item id="1" parent="1"/><expanded_item id="2" parent="1"/><expanded_item id="3" parent="1"/></tab_structure><tab_browse><table title="booth" custom_title="0" dock_id="2" table="4,5:mainbooth"/><dock_state state="000000ff00000000fd000000010000000200000536000003a5fc0100000002fb000000160064006f0063006b00420072006f00770073006500310100000000ffffffff0000000000000000fb000000160064006f0063006b00420072006f00770073006500320100000000000005360000012300ffffff000005360000000000000004000000040000000800000008fc00000000"/><default_encoding codec=""/><browse_table_settings><table schema="main" name="booth" show_row_id="0" encoding="" plot_x_axis="" unlock_view_pk="_rowid_" freeze_columns="0"><sort/><column_widths><column index="1" value="136"/><column index="2" value="164"/><column index="3" value="300"/><column index="4" value="108"/></column_widths><filter_values/><conditional_formats/><row_id_formats/><display_formats/><hidden_columns/><plot_y_axes/><global_filter/></table></browse_table_settings></tab_browse><tab_sql><sql name="INSERT_UPDATE_DELETE">/* MODULE 5 */
<?xml version="1.0" encoding="UTF-8"?><sqlb_project><window><main_tabs open="structure browser pragmas query" current="3"/></window><tab_structure><column_width id="0" width="300"/><column_width id="1" width="0"/><column_width id="2" width="100"/><column_width id="3" width="12168"/><column_width id="4" width="0"/><expanded_item id="0" parent="1"/><expanded_item id="1" parent="1"/><expanded_item id="2" parent="1"/><expanded_item id="3" parent="1"/></tab_structure><tab_browse><table title="booth" custom_title="0" dock_id="2" table="4,5:mainbooth"/><dock_state state="000000ff00000000fd0000000100000002000004a4000003a5fc0100000002fb000000160064006f0063006b00420072006f00770073006500310100000000ffffffff0000000000000000fb000000160064006f0063006b00420072006f00770073006500320100000000000004a40000012300ffffff000004a40000000000000004000000040000000800000008fc00000000"/><default_encoding codec=""/><browse_table_settings/></tab_browse><tab_sql><sql name="INSERT_UPDATE_DELETE*">/* MODULE 5 */
/* INSERT UPDATE DELETE */


Expand Down Expand Up @@ -45,30 +45,18 @@ CREATE TEMP TABLE product_expanded AS



</sql><sql name="update_statements_for_view">/* MODULE 5 */
/* UPDATE statements for view */
</sql><sql name="dynamic_view">/* MODULE 5 */
/* DYNAMIC VIEW */


/* 1. SET market_date equal to today for new_customer_purchases */




/* 2. Add today's info to the market_date_info

we need to add
1. today's date
2. today's day
3. today's week number
4. today's year

INSERT INTO market_date_info
VALUES('....','....','....','....','8:00 AM','2:00 PM','nothing interesting','Summer','25','28',0,0);

*/

</sql><sql name="dynamic_view">/* MODULE 5 */
/* DYNAMIC VIEW */
/* spoilers below */



Expand All @@ -78,7 +66,6 @@ VALUES('....','....','....','....','8:00 AM','2:00 PM','nothing interesting','Su



/* spoilers below */



Expand All @@ -87,24 +74,37 @@ VALUES('....','....','....','....','8:00 AM','2:00 PM','nothing interesting','Su



-- THIS ONLY WORKS IF YOU HAVE DONE THE PROPER STEPS FOR IMPORTING
-- 1) update new_customer_purchases to today
-- 2) add the union
-- 3) add the where statement
-- 4) update the market_date_info to include today




</sql><sql name="update_statements_for_view">/* MODULE 5 */
/* UPDATE statements for view */


/* 1. SET market_date equal to today for new_customer_purchases */



-- THIS ONLY WORKS IF YOU HAVE DONE THE PROPER STEPS FOR IMPORTING
-- 1) update new_customer_purchases to today
-- 2) add the union
-- 3) add the where statement
-- 4) update the market_date_info to include today

/* 2. Add today's info to the market_date_info

we need to add
1. today's date
2. today's day
3. today's week number
4. today's year

INSERT INTO market_date_info
VALUES('....','....','....','....','8:00 AM','2:00 PM','nothing interesting','Summer','25','28',0,0);

*/

</sql><sql name="CROSS_JOIN">/* MODULE 5 */
/* CROSS JOIN */

Expand Down
2 changes: 1 addition & 1 deletion 04_this_cohort/custom_slides/markdown/slides_01.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ class: left, top, inverse
### Course Tools
- [DB Browser for SQLite](https://sqlitebrowser.org/dl/): *Where we will write code*
- [GitHub](https://github.com/UofT-DSI/sql): *Module Overview*
- [Etherpad](https://pad.riseup.net/p/SQL_DSI_SGS_Oct2025): *Where we will keep track of session progress*
- [Etherpad](https://pad.riseup.net/p/SQL_DSI_Nov2025): *Where we will keep track of session progress*
- **Visit and complete the sign in prompt at the start every session**
- [SQLite documentation](https://www.sqlite.org/index.html): *For SQL specific questions*
- [DrawIO](https://www.drawio.com/) or [Lucid](https://www.lucidchart.com/pages/): *For Assignments*
Expand Down
2 changes: 1 addition & 1 deletion 04_this_cohort/custom_slides/markdown/slides_01.html
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@
### Course Tools
- [DB Browser for SQLite](https://sqlitebrowser.org/dl/): *Where we will write code*
- [GitHub](https://github.com/UofT-DSI/sql): *Module Overview*
- [Etherpad](https://pad.riseup.net/p/SQL_DSI_SGS_Oct2025): *Where we will keep track of session progress*
- [Etherpad](https://pad.riseup.net/p/SQL_DSI_Nov2025): *Where we will keep track of session progress*
- **Visit and complete the sign in prompt at the start every session**
- [SQLite documentation](https://www.sqlite.org/index.html): *For SQL specific questions*
- [DrawIO](https://www.drawio.com/) or [Lucid](https://www.lucidchart.com/pages/): *For Assignments*
Expand Down
Binary file modified 04_this_cohort/custom_slides/pdf/slides_01.pdf
Binary file not shown.
31 changes: 31 additions & 0 deletions 04_this_cohort/live_code/Cohort_8/module_2/CASE_WHEN.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/* MODULE 2 */
/* CASE */


SELECT *,
/* 1. Add a CASE statement declaring which days vendors should come */
CASE WHEN vendor_type = 'Fresh Focused' THEN 'Wednesday'
WHEN vendor_type = 'Prepared Foods' THEN 'Thursday'
ELSE 'Saturday'
END as day_of_specialty

/* 2. Add another CASE statement for Pie Day */
,CASE WHEN vendor_name = "Annie's Pies" -- double quotes will work just this once
THEN 'Annie is the best'
END AS annie_is_queen


/* 3. Add another CASE statement with an ELSE clause to handle rows evaluating to False */
,CASE WHEN vendor_name LIKE '%pie%'
THEN 'Wednesday'
ELSE 'Friday' -- with this else, we get values for all the FALSE statements
END AS pie_day


/* 4. Experiment with selecting a different column instead of just a string value */
,CASE WHEN vendor_type = 'Fresh Focused' THEN vendor_owner_first_name
WHEN vendor_type = 'Eggs & Meats' THEN vendor_owner_last_name
END as first_or_last


FROM vendor
Loading