Recursive Common Table Expressions
Recursive Common Table Expressions
AllSupplierPartPairs AS
(
SELECT *
FROM Suppliers, Parts
),
SELECT
employee_id,
first_name,
last_name,
1 AS lvl
FROM
employees
WHERE manager_id IS NULL
SELECT
e.employee_id,
e.first_name,
e.last_name,
lvl + 1 AS lvl
FROM
RCTE INNER JOIN employees e
ON (RCTE.employee_id = e.manager_id)
)
-- SEARCH DEPTH FIRST BY employee_id ASC SET seq#
UNION ALL
SELECT
ID,
Name,
Price,
Price AS DiscountedPrice,
0 AS DiscountAmount,
0 AS DiscountRate,
CAST(' ' AS VARCHAR2(1024)) AS CouponNames,
0 AS CouponCount,
-1 AS CouponId
FROM
Iggyproducts
Fernandez Database Specialists 28
Coupon Clipping
UNION ALL
SELECT
RCTE.ID, RCTE.Name, RCTE.Price,
DECODE(C.IsPercent, 'N', RCTE.DiscountedPrice - C.Value,
RCTE.DiscountedPrice - (RCTE.DiscountedPrice / 100 *
C.Value)) DiscountedPrice,
RCTE.Price - DiscountedPrice AS DiscountAmount,
(RCTE.Price - DiscountedPrice) / RCTE.Price * 100 AS
DiscountRate,
DECODE(RCTE.CouponNames, ' ', C.Name, RCTE.CouponNames
|| ' + ' || C.Name) AS CouponNames,
RCTE.CouponCount + 1 AS CouponCount,
C.ID AS CouponID
FROM RCTE, coupons C
WHERE
c.id > RCTE.CouponID AND CouponCount <= 2 AND
DiscountAmount <= 30 AND DiscountRate <= 30
),
Iggy Fernandez Database Specialists 29
Coupon Clipping
SortedPrices AS
(
SELECT
RCTE.*,
RANK() OVER (PARTITION BY ID ORDER BY DiscountedPrice)
AS Rank
FROM RCTE
)
SELECT
ID, Name, Price,
DiscountedPrice, DiscountAmount, DiscountRate,
CouponNames
FROM SortedPrices
WHERE Rank = 1
ORDER BY ID;