About me:Oracle ACE pro,optimistic,passionate and harmonious.
Focus on ORACLE,MySQL and other database programming,peformance tuning,db design, j2ee,Linux/AIX,Architecture tech,etc
--只考虑2008年前3月,如需详细学习MODEL子句,请参考相关文档,MODEL很强大,可以实现很多复杂功能
SELECT years,months,product_name,NVL(sales,0)
FROM t
MODEL
PARTITION BY (product_name)
DIMENSION BY (years,months)
MEASURES(sales)
RULES (sales[2008, FOR months IN (1,2,3)] = sales[2008,CV()])
ORDER BY 1,2,3;
SELECT m.years,m.months,t.product_name,NVL(t.sales,0) sales
FROM t
RIGHT JOIN
(SELECT DISTINCT years,months FROM t) m
PARTITION BY (t.product_name)
ON t.years = m.years
AND t.months = m.months
ORDER BY 1,2,3;
这个语句不会报错,但是结果:
YEARS MONTHS PRODUCT_NAME SALES
---------- ---------- -------------------- ----------
2008 1 A 1000
2008 1 B 1500
2008 2 A 2000
2008 2 B 3000
2008 2 C 1000
2008 3 A 3000 已选择6行。
DINGJUN123>SELECT m.years,m.months,t.product_name,NVL(t.sales,0) sales
2 FROM t
3 LEFT JOIN
4 (SELECT DISTINCT years,months FROM t) m
5 PARTITION BY (t.product_name)
6 ON t.years = m.years
7 AND t.months = m.months
8 ORDER BY 1,2,3;
PARTITION BY (t.product_name)
*
第 5 行出现错误:
ORA-00904: : 标识符无效
--使用分析函数对比产品当前月销售与上月销售情况,计算递增量,可以对决策支持提供很清晰的报表
SELECT years,months,product_name,sales,
sales-NVL(LAG(sales)
OVER(PARTITION BY product_name
ORDER BY years,months)
,0) add_last_sales
FROM
(
SELECT m.years,m.months,t.product_name,NVL(t.sales,0) sales
FROM
(SELECT DISTINCT years,months FROM t) m
LEFT JOIN
t PARTITION BY (t.product_name)
ON t.years = m.years
AND t.months = m.months
);
结果如下:
PRODUCT_NAME DONE_DATE SALES RECENT_SALES
-------------------- ---------- ---------- ------------
A 2010-07-01 1000 1000
A 2010-07-02 1000
A 2010-07-03 1000
A 2010-07-04 1000
A 2010-07-05 2000 2000
B 2010-07-01
B 2010-07-02 3000 3000
B 2010-07-03 3000
B 2010-07-04 4000 4000
B 2010-07-05 4000
已选择10行。