Cost and Common Table Expressions (CTEs)

Analyzing Business Data in SQL

Michel Semaan

Data Scientist

Cost

  • The money that a company spends
  • Examples
    • Employee salaries
    • Delivery fleet acquisition and maintenance
    • Meal costs
Analyzing Business Data in SQL

Tables you'll need

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
...       ...                         ...         ...

stock

stocking_date  meal_id   stocked_quantity
-------------  --------  ----------------
2018-06-01     0         76               
2018-06-01     1         42               
2018-06-01     2         56
...            ...       ...
Analyzing Business Data in SQL

Calculating cost

Query

SELECT
  meals.meal_id, 
  SUM(meal_cost * stocked_quantity) AS cost 
FROM meals
JOIN stock ON meals.meal_id = stock.meal_id
GROUP BY meals.meal_id
ORDER BY meals.cost DESC
LIMIT 3;

Result

meal_id  cost      
  --------
9        3820.0
7        3592.5    
8        2332.5    
Analyzing Business Data in SQL

How do you combine revenue and cost?

  • Profit = Revenue - Cost
  • The individual queries for revenue and cost have been written
Analyzing Business Data in SQL

Common Table Expressions (CTEs)

  • Store a query's results in a temporary table
  • Reference the temporary table in a following query

Query

WITH table_1 AS
  (SELECT ...
   FROM ...),
  table_2 AS
  (SELECT ...
   FROM   ...)

SELECT ...
FROM table_1
JOIN table_2 ON ...
...
Analyzing Business Data in SQL

CTEs in action

Query

WITH costs_and_quantities AS (
 SELECT
   meals.meal_id,
   SUM(stocked_quantity) AS quantity,
   SUM(meal_cost * stocked_quantity) AS cost
 FROM meals
 JOIN stock ON meals.meal_id = stock.meal_id
 GROUP BY meals.meal_id)

SELECT meal_id, quantity, cost FROM costs_and_quantities ORDER BY cost DESC LIMIT 3;

Result

meal_id  quantity  cost      
-------  --------  -------
5        3062      12248     
4        3142      10211.5   
6        2989      8219.75
Analyzing Business Data in SQL

Cost and Common Table Expressions (CTEs)

Analyzing Business Data in SQL

Preparing Video For Download...