Region Report

Write a procedure region_report(p_region) that, for the customers of a region, prints the shipper used for the most orders and the 10 products bought in the largest quantity.

Uses the Northwind sample data: load ../northwind/northwind.sql first, then run solution.sql.

Example

region_report('AK'):

Most used shipper in AK: Federal Shipping (5 orders)
Top products in AK:
  Pavlova (120)
  Lakkalikööri (50)
  Schoggi Schokolade (50)
  Gnocchi di nonna Alice (44)
  Singaporean Hokkien Fried Mee (40)
  Gorgonzola Telino (34)
  Chartreuse verte (30)
  Escargots de Bourgogne (30)
  Carnarvon Tigers (25)
  Thüringer Rostbratwurst (25)

Approach

Two grouped queries. The shipper is the first row of orders grouped by shipper, ordered by count, read with SELECT INTO from a subquery filtered by ROWNUM = 1. The top products use FETCH FIRST 10 ROWS ONLY on quantities grouped by product.

Ties (two products at 50, two at 25) have no defined order unless the query gives one; ordering by quantity and then name makes the output repeatable. A region with no orders makes the first SELECT INTO raise NO_DATA_FOUND, handled with a message.

ROWNUM = 1 must be applied outside the subquery that sorts: ROWNUM is assigned before ORDER BY in the same query block.

Lesson: PL/SQL blocks, procedures and exceptions.

Solutions

-- Needs the Northwind tables: run ../northwind/northwind.sql first.
SET SERVEROUTPUT ON FORMAT WRAPPED
SET FEEDBACK OFF

CREATE OR REPLACE PROCEDURE region_report(p_region customers.Region%TYPE) IS
    v_shipper shippers.CompanyName%TYPE;
    v_orders  NUMBER;
BEGIN
    SELECT CompanyName, n INTO v_shipper, v_orders FROM (
        SELECT s.CompanyName, count(*) AS n
        FROM orders o
        JOIN customers c ON c.CustomerID = o.CustomerID
        JOIN shippers s  ON s.ShipperID = o.ShipVia
        WHERE c.Region = p_region
        GROUP BY s.ShipperID, s.CompanyName
        ORDER BY n DESC, s.CompanyName
    ) WHERE ROWNUM = 1;
    DBMS_OUTPUT.PUT_LINE('Most used shipper in ' || p_region || ': ' || v_shipper || ' (' || v_orders || ' orders)');

    DBMS_OUTPUT.PUT_LINE('Top products in ' || p_region || ':');
    FOR p IN (
        SELECT pr.ProductName, sum(d.Quantity) AS q
        FROM orders o
        JOIN customers c      ON c.CustomerID = o.CustomerID
        JOIN order_details d  ON d.OrderID = o.OrderID
        JOIN products pr      ON pr.ProductID = d.ProductID
        WHERE c.Region = p_region
        GROUP BY pr.ProductID, pr.ProductName
        ORDER BY q DESC, pr.ProductName
        FETCH FIRST 10 ROWS ONLY
    ) LOOP
        DBMS_OUTPUT.PUT_LINE('  ' || p.ProductName || ' (' || p.q || ')');
    END LOOP;
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        DBMS_OUTPUT.PUT_LINE('No orders from region ' || p_region);
END;
/

EXEC region_report('AK')