Chapter 4. Statistics, analytic, OLAP functions in business scenarios 167
4.2.6 Determine the most profitable items and where they are sold
Being able to determine one’s most profitable items and where they are sold
enables an organization to optimize product purchases and product distribution
for maximum profitability.
To establish the profit on an item you need to know its cost to you and the price at
which it is sold. In this example we will use the sales figures from a fictional
world-wide Coffee Retailer and cross calculate the profit based on the profit of
these items in their respective countries.
Data
Our data is mainly taken from pricing and transactions.
? The PRICING view includes store, item, and sales information.
? The TRANSACTIONS view includes store, item, cost, and price sold.
BI functions showcased
RANK, OVER, PARTITION BY, ORDER BY
Steps
This query is answered via multiple steps as follows:
1. For each variety of coffee, determine the store with the highest profit.
2. For each store, determine the coffee variety with the highest profit.
3. Determine the most profitable product in each store.
4. Determine the most profitable store for each variety of coffee.
Step 1
The query shown in Example 4-12 calculates the store with the highest profit on
the different varieties of coffee:
Example 4-12 Store with the highest profit on the different varieties of coffee
SELECT store, item, profit
FROM
(
SELECT store, item, price - cost AS profit,
RANK() OVER (PARTITION BY item ORDER BY price - cost DESC) AS
rank_profit
FROM pricing
) AS ranked_profit
WHERE rank_profit = 1
ORDER BY profit DESC