forked from UofT-DSI/sql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassignment2.sql
More file actions
243 lines (196 loc) · 8.57 KB
/
assignment2.sql
File metadata and controls
243 lines (196 loc) · 8.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/* ASSIGNMENT 2 */
/* SECTION 2 */
-- COALESCE
/* 1. Our favourite manager wants a detailed long list of products, but is afraid of tables!
We tell them, no problem! We can produce a list with all of the appropriate details.
Using the following syntax you create our super cool and not at all needy manager a list:
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.
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.) */
SELECT
product_name || ', ' || COALESCE(product_size, '') || ' (' || COALESCE(product_qty_type, 'unit') || ')' AS [Product_List]
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(). */
SELECT
customer_id,
market_date,
dense_rank() 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. */
SELECT
customer_id,
market_date,
dense_rank() over (PARTITION by customer_id ORDER by market_date DESC) AS Visit_Number
FROM customer_purchases;
SELECT
customer_id,
market_date
FROM (
SELECT
customer_id,
market_date,
dense_rank() over (PARTITION by customer_id ORDER by market_date DESC) AS Visit_Number
FROM customer_purchases;
) AS Recent_visit_number
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. */
SELECT
customer_id,
market_date,
product_id,
COUNT(*) OVER (PARTITION BY customer_id, product_id) AS Product_purchase
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!
| product_name | description |
|----------------------------|-------------|
| 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
/* 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. */
WITH total_sale_by_date AS (
SELECT
market_date,
SUM(quantity * cost_to_customer_per_qty) AS total_sale
FROM customer_purchases
GROUP BY market_date
),
ranked_sales AS (
SELECT
market_date,
total_sale,
RANK() OVER (ORDER BY total_sale DESC) AS best_rank,
RANK() OVER (ORDER BY total_sale ASC) AS worst_rank
FROM total_sale_by_date
),
best_sale_date AS (
SELECT market_date, total_sale
FROM ranked_sales
WHERE best_rank = 1
),
worst_sale_date AS (
SELECT market_date, total_sale
FROM ranked_sales
WHERE worst_rank = 1
)
SELECT market_date, total_sale, 'date of best sale' AS description
FROM best_sale_date
UNION
SELECT market_date, total_sale, 'date of worst sale' AS description
FROM worst_sale_date;
/* SECTION 3 */
-- Cross Join
/*1. Suppose every vendor in the `vendor_inventory` table had 5 of each of their products to sell to **every**
customer on record. How much money would each vendor make per product?
Show this by vendor_name and product name, rather than using the IDs.
HINT: Be sure you select only relevant columns and rows.
Remember, CROSS JOIN will explode your table rows, so CROSS JOIN should likely be a subquery.
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). */
WITH VendorProductCustomer AS (
SELECT
v.vendor_id,
v.vendor_name,
p.product_name,
vi.original_price * 5 AS money_per_product, -- Assuming 5 products sold per vendor-customer pair
c.customer_id
FROM
vendor_inventory vi
INNER JOIN vendor v ON vi.vendor_id = v.vendor_id
INNER JOIN product p ON vi.product_id = p.product_id
CROSS JOIN customer c -- Cross join to simulate each customer purchasing from every vendor
)
SELECT
vendor_name,
product_name,
SUM(money_per_product) AS total_money
FROM
VendorProductCustomer
GROUP BY
vendor_name,
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
VALUES (35, 'Apple Pie', 'Medium', 2, 'unit',CURRENT_TIMESTAMP);
-- DELETE
/* 1. Delete the older record for the whatever product you added. 0
HINT: If you don't specify a WHERE clause, you are going to have a bad time.*/
DELETE FROM product_units
WHERE product_id = 35;
-- 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.
ALTER TABLE product_units
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_quantity INT;
UPDATE product_units
SET current_quantity = (
SELECT COALESCE(x.quantity, 0) AS quantity
FROM (
SELECT pu.product_id, v.quantity, v.market_date,
RANK() OVER (PARTITION BY v.product_id ORDER BY v.market_date DESC) as rank
FROM product_units AS pu
LEFT JOIN vendor_inventory AS v ON pu.product_id = v.product_id
) AS x
WHERE x.rank = 1
AND product_units.product_id = x.product_id);