Sie sind auf Seite 1von 1

Chapter 3: Selecting 97

-- Determine the worst year for total sales.

SELECT FIRST
YEAR ( sales_order.order_date )
INTO @worst_year
FROM product
INNER JOIN sales_order_items
ON product.id = sales_order_items.prod_id
INNER JOIN sales_order
ON sales_order_items.id = sales_order.id
GROUP BY YEAR ( sales_order.order_date )
ORDER BY SUM ( sales_order_items.quantity * product.unit_price ) ASC;

-- Find the second- and third-best sales for a single color on a


-- single day in the worst year.

SELECT TOP 2 START AT 2


product.color AS best_color,
sales_order.order_date AS best_day,
SUM ( sales_order_items.quantity * product.unit_price ) AS sales_amount,
NUMBER(*) + 1 AS rank
FROM product
INNER JOIN sales_order_items
ON product.id = sales_order_items.prod_id
INNER JOIN sales_order
ON sales_order_items.id = sales_order.id
WHERE YEAR ( sales_order.order_date ) = @worst_year
GROUP BY product.color,
sales_order.order_date
ORDER BY SUM ( sales_order_items.quantity * product.unit_price ) DESC;
END;
The first SELECT in the procedure puts a single value into the variable
@worst_year. The second query doesnt have an INTO clause, so its result set is
implicitly returned to the caller when the procedure is called.
You can test this procedure in ISQL as follows:
CALL p_best_losers_in_worst_year();
Here are the second- and third-best color days, together with the sales amounts,
as returned by the procedure call:
best_color best_day sales_amount rank
========== ========== ============ ====
Green 2001-03-24 1728.00 2
Black 2001-03-17 1524.00 3
The third step in the solution uses the procedure call as a table term in the
FROM clause of a query to find the product details:
SELECT DISTINCT
product.id,
product.name,
product.description,
product.color,
best_loser.rank
FROM p_best_losers_in_worst_year() AS best_loser
INNER JOIN product
ON product.color = best_loser.best_color
INNER JOIN sales_order_items
ON product.id = sales_order_items.prod_id
INNER JOIN sales_order
ON sales_order_items.id = sales_order.id

Das könnte Ihnen auch gefallen