Chapter 4. Statistics, analytic, OLAP functions in business scenarios 193
Example 4-29 Customer usage profile view
CREATE VIEW profile(cust_id, avg_amt, sd_amt) AS
SELECT cust_id, AVG(charge_amt), STDDEV(charge_amt)
FROM custtrans
WHERE date BETWEEN '2002-01-01' and '2002-03-31'
GROUP BY cust_id
Step 2
Detect and flag unusually large charges by writing them to the BIG_CHARGES
table as shown in Example 4-30.
Example 4-30 Detect & flag unusually large charges
CREATE TRIGGER big_chrg
AFTER INSERT ON custtrans
REFERENCING NEW AS newrow FOR EACH ROW MODE DB2SQL
WHEN (newrow.charge_amt > (SELECT avg_amt + 2e0 * sd_amt
FROM profile
WHERE profile.cust_id = newrow.cust_id))
INSERT INTO big_charges(cust_id,charge_amt)
VALUES(newrow.cust_id, newrow.charge_amt)
Here the incoming transaction’s charge amount is checked to see whether it
exceeds twice the standard deviation value above the average for this customer,
and writes this transaction to the BIG_CHARGES table if true.
Another trigger (not shown here) needs to be written for the BIG_CHARGES
table which sets off alarms when the number of such charges over a given period
exceeds pre-defined thresholds.
4.3.6 Plot monthly stock prices movement with percentage change
The objective is to determine the average price of the stock per month and its
percentage change over the previous month. This information can be used for
trend analysis for making investment decisions.
In our example, we use the stock price data for a 6-month period.
Data
The main attributes are stock symbol, date, and closing price of the stock on that
date.
BI functions showcased
OVER, ORDER BY, ROWS BETWEEN