Analyzing Business Data in SQL
Michel Semaan
Data Scientist
meals
meal_id eatery meal_price meal_cost
------- ------------------------ ---------- ---------
0 'Leaning Tower of Pizza' 4 2
1 'Leaning Tower of Pizza' 3.5 1.25
2 'Leaning Tower of Pizza' 4.5 1.75
... ... ... ...
orders
order_date user_id order_id meal_id order_quantity
---------- ------- -------- ------- --------------
2018-06-01 0 0 4 3
2018-06-01 0 0 14 2
2018-06-01 0 0 15 1
... ... ... ... ...
Example order
Revenue: Multiply each meal's price times its ordered quantity, then sum the results
Query
SELECT
order_id,
SUM(meal_price * order_quantity) AS revenue
FROM meals
JOIN orders ON meals.meal_id = orders.meal_id
GROUP BY order_id;
DATE_TRUNC(date_part, date)
DATE_TRUNC('week', '2018-06-12') :: DATE
→ '2018-06-11'
DATE_TRUNC('month', '2018-06-12') :: DATE
→ '2018-06-01'
DATE_TRUNC('quarter', '2018-06-12') :: DATE
→ '2018-04-01'
DATE_TRUNC('year', '2018-06-12') :: DATE
→ '2018-01-01'
Analyzing Business Data in SQL