-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcase.sql
61 lines (53 loc) · 3.1 KB
/
case.sql
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
/*
BACKGROUND:
The following schema is a subset of a relational database of a grocery store
chain. This chain sells many products of different product classes to its
customers across its different stores. It also conducts many different
promotion campaigns.
The relationship between the four tables we want to analyze is depicted below:
# sales # products
+------------------+---------+ +---------------------+---------+
| product_id | INTEGER |>--------| product_id | INTEGER |
| store_id | INTEGER | +---<| product_class_id | INTEGER |
| customer_id | INTEGER | | | brand_name | VARCHAR |
+---<| promotion_id | INTEGER | | | product_name | VARCHAR |
| | store_sales | DECIMAL | | | is_low_fat_flg | TINYINT |
| | store_cost | DECIMAL | | | is_recyclable_flg | TINYINT |
| | units_sold | DECIMAL | | | gross_weight | DECIMAL |
| | transaction_date | DATE | | | net_weight | DECIMAL |
| +------------------+---------+ | +---------------------+---------+
| |
| # promotions | # product_classes
| +------------------+---------+ | +---------------------+---------+
+----| promotion_id | INTEGER | +----| product_class_id | INTEGER |
| promotion_name | VARCHAR | | product_subcategory | VARCHAR |
| media_type | VARCHAR | | product_category | VARCHAR |
| cost | DECIMAL | | product_department | VARCHAR |
| start_date | DATE | | product_family | VARCHAR |
| end_date | DATE | +---------------------+---------+
+------------------+---------+
*/
/*
PROMPT:
-- Of sales that had a valid promotion, the VP of marketing
-- wants to know what % of transactions occur on either
-- the very first day or the very last day of a promotion campaign.
EXPECTED OUTPUT:
Note: Please use the column name(s) specified in the expected output in your solution.
+-------------------------------------------------------------+
| pct_of_transactions_on_first_or_last_day_of_valid_promotion |
+-------------------------------------------------------------+
| 41.9047619047619048 |
+-------------------------------------------------------------+
-------------- PLEASE WRITE YOUR SQL SOLUTION BELOW THIS LINE ----------------
*/
SELECT
(100.0 * (SELECT count(transaction_date)
FROM promotions
JOIN sales
ON sales.promotion_id = promotions.promotion_id
WHERE sales.transaction_date = promotions.start_date OR sales.transaction_date = promotions.end_date) / (count(transaction_date))) as pct_of_transactions_on_first_or_last_day_of_valid_promotion
FROM promotions
JOIN sales
ON sales.promotion_id = promotions.promotion_id
WHERE sales.transaction_date >= promotions.start_date AND sales.transaction_date <= promotions.end_date;