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
212 changes: 211 additions & 1 deletion 02_activities/assignments/Cohort_8/Assignment2.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,36 @@ There are several tools online you can use, I'd recommend [Draw.io](https://www.

**HINT:** You do not need to create any data for this prompt. This is a logical model (ERD) only.


![alt text](image-prompt1&2-1.png)
![alt text](image-prompt1&2-1.png)


#### Prompt 2
We want to create employee shifts, splitting up the day into morning and evening. Add this to the ERD.



See above




#### Prompt 3
The store wants to keep customer addresses. Propose two architectures for the CUSTOMER_ADDRESS table, one that will retain changes, and another that will overwrite. Which is type 1, which is type 2?

**HINT:** search type 1 vs type 2 slowly changing dimensions.

```
Your answer...
![alt text](image-prompt3.png)

image-prompt3.png






```

***
Expand Down Expand Up @@ -88,19 +108,72 @@ Find the NULLs and then using COALESCE, replace the NULL with a blank for the fi

<div align="center">-</div>

Answer

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




#### Windowed Functions
1. Write a query that selects from the customer_purchases table and numbers each customer’s visits to the farmer’s market (labeling each market date with a different number). Each customer’s first visit is labeled 1, second visit is labeled 2, etc.

You can either display all rows in the customer_purchases table, with the counter changing on 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().


answer

SELECT
customer_id,
market_date,
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.

answer

SELECT
customer_id,
market_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date DESC) AS visit_number
FROM customer_purchases


query2
SELECT *
FROM (
SELECT
customer_id,
market_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY market_date DESC) AS visit_number
FROM customer_purchases
) AS ranked_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.

<div align="center">-</div>


answer

SELECT
customer_id,
product_id,
market_date,
COUNT(*) OVER (PARTITION BY customer_id, product_id) AS product_purchase_count
FROM customer_purchases;

#### String manipulations
1. Some product names in the product table have descriptions like "Jar" or "Organic". These are separated from the product name with a hyphen. Create a column using SUBSTR (and a couple of other commands) that captures these, but is otherwise NULL. Remove any trailing or leading whitespaces. Don't just use a case statement for each product!

Expand All @@ -110,17 +183,64 @@ You can either display all rows in the customer_purchases table, with the counte

**HINT**: you might need to use INSTR(product_name,'-') to find the hyphens. INSTR will help split the column.


answer

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.

<div align="center">-</div>

answer

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.

**HINT**: There are a possibly a few ways to do this query, but if you're struggling, try the following: 1) Create a CTE/Temp Table to find sales values grouped dates; 2) Create another CTE/Temp table with a rank windowed function on the previous query to create "best day" and "worst day"; 3) Query the second temp table twice, once for the best day, once for the worst day, with a UNION binding them.

***


answer


WITH date_sales AS (
SELECT
market_date,
SUM(quantity * cost_to_customer_per_qty) AS total_sales
FROM customer_purchases
GROUP BY market_date
),
ranked_dates 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 date_sales
)
SELECT market_date, total_sales, 'Best Day' AS category
FROM ranked_dates
WHERE best_rank = 1

UNION

SELECT market_date, total_sales, 'Worst Day' AS category
FROM ranked_dates
WHERE worst_rank = 1;

## Section 3:
You can start this section following *session 5*.

Expand All @@ -139,11 +259,71 @@ Steps to complete this part of the assignment:

<div align="center">-</div>


answer


WITH vendor_products AS (
SELECT
vi.vendor_id,
vi.product_id,
original_price,
v.vendor_name,
p.product_name
FROM vendor_inventory vi
JOIN vendor v ON vi.vendor_id = v.vendor_id
JOIN product p ON vi.product_id = p.product_id
),
all_customers AS (
SELECT customer_id FROM customer
)
SELECT
vp.vendor_name,
vp.product_name,
SUM(5 * original_price) AS total_revenue
FROM vendor_products vp
CROSS JOIN all_customers ac
GROUP BY vp.vendor_name, vp.product_name
ORDER BY vp.vendor_name, vp.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`.

answer



CREATE TABLE product_units AS
SELECT
p.*,
CURRENT_TIMESTAMP AS snapshot_timestamp
FROM product p
WHERE product_qty_type = 'unit';


2. Using `INSERT`, add a new row to the product_unit table (with an updated timestamp). This can be any product you desire (e.g. add another record for Apple Pie).


answer


INSERT INTO product_units (
product_id,
product_name,
product_size,
product_category_id,
product_qty_type,
snapshot_timestamp
)
VALUES (
999,
'Apple Pie',
'10 inch',
'7',
'unit',
CURRENT_TIMESTAMP
);

<div align="center">-</div>

#### DELETE
Expand All @@ -152,6 +332,10 @@ Steps to complete this part of the assignment:
**HINT**: If you don't specify a WHERE clause, [you are going to have a bad time](https://imgflip.com/i/8iq872).

<div align="center">-</div>
answer

DELETE FROM product_units
WHERE product_id = '999';

#### UPDATE
1. We want to add the current_quantity to the product_units table. First, add a new column, `current_quantity` to the table using the following syntax.
Expand All @@ -163,3 +347,29 @@ ADD current_quantity INT;
Then, using `UPDATE`, change the current_quantity equal to the **last** `quantity` value from the vendor_inventory details.

**HINT**: This one is pretty hard. First, determine how to get the "last" quantity per product. Second, coalesce null values to 0 (if you don't have null values, figure out how to rearrange your query so you do.) Third, `SET current_quantity = (...your select statement...)`, remembering that WHERE can only accommodate one column. 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_quantitys INT;

SELECT product_id,
COALESCE(quantity, 0) AS last_quantity
FROM (
SELECT product_id,
quantity,
ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY market_date DESC) AS rn
FROM vendor_inventory
) t
WHERE rn = 1;

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


Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?><sqlb_project><db path="Baruni Prabaharan Assignment 1.db" readonly="0" foreign_keys="0" case_sensitive_like="0" temp_store="0" wal_autocheckpoint="1000" synchronous="2"/><attached/><window><main_tabs open="structure browser pragmas query" current="1"/></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="419"/><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="assignment1" custom_title="0" dock_id="1" table="4,11:mainassignment1"/><dock_state state="000000ff00000000fd00000001000000020000033b00000276fc0100000001fb000000160064006f0063006b00420072006f007700730065003101000000000000033b0000012400ffffff000002580000000000000004000000040000000800000008fc00000000"/><default_encoding codec=""/><browse_table_settings><table schema="main" name="assignment1" show_row_id="0" encoding="" plot_x_axis="" unlock_view_pk="_rowid_" freeze_columns="0"><sort/><column_widths><column index="1" value="725"/></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="SQL 1*">SELECT *
FROM customer_purchases
WHERE product_id IN (4, 9);
</sql><current_tab id="0"/></tab_sql></sqlb_project>
Expand Down
Loading