Oracle模式SQL基础知识
Oracle模式SQL基础知识
Sql代码
--创建用于测试的表及数据
create table t603
(
code varchar2(10),
year varchar2(10),
month varchar2(10),
p_id varchar2(7),
v1 number(10),
v2 number(10)
);
comment on column t603.code is '工厂';
comment on column t603.year is '年份';
comment on column t603.month is '月份';
comment on column t603.p_id is '产品';
comment on column t603.v1 is '生产量';
comment on column t603.v2 is '销售量';
insert into t603 values('600001',2012,11,'30',1,1);
insert into t603 values('600001',2012,11,'31',1,1);
insert into t603 values('600001',2012,11,'10',2,2);
insert into t603 values('600002',2012,12,'10',3,2);
insert into t603 values('600002',2012,12,'31',2,1);
insert into t603 values('600002',2012,12,'30',2,1);
select * from t603;
--按自定义的规则聚合
Sql代码
select code,
p_id,
v1
from t603
where code in ('600001', '600002')
model return updated rows --MODEL后面的RETURN UPDATED ROWS子句将结果限制为在该查询中创建或更新的那些行,使结果集只包含新计算的值。
partition by(code) --分区
dimension by(p_id) --维度
measures(v1) --度量
rules (v1['err1'] = v1['30'] + v1['31'] - v1['10']) --计算规则
order by code, p_id;
输出 CODEP_IDV1
1600001err10
2600002err11
--按多个规则聚合,返回包括非聚合行
Sql代码
select code,
year,
p_id,
month,
v1
from t603
where year = '2012'
model
partition by (code,year)
dimension by (p_id,month)
measures (v1,v2)
rules (
v1['err1',11] = v1['30',11] + v1['31',11] - v1['10',11],
v2['err1',12] = v2['30',12] + v2['31',12] - v2['10',12])
order by code, p_id;
输出 CODEYEARP_IDMONTHV1
1600001201210112
2600001201230111
3600001201231111
46000012012err112
56000012012err1110
6600002201210123
7600002201230122
8600002201231122
96000022012err112
106000022012err111
--指定要聚合的维值
Sql代码
select code,
p_id,
month,
v1
from t603
where year = '2012'
model return updated rows
partition by (code)
dimension by (p_id,month)
measures (v1)
rules (
v1['err1',for month in(11,12)] = v1['30',cv(month)] + v1['31',cv(month)] -v1['10',cv(month)])
order by code, p_id, month;
输出 CODEP_IDMONTHV1
1600001err1110
2600001err112
3600002err111
4600002err1121
--CV()函数获取多行统计记录的当前值,可以使用表达式进行计算
--为数值型可用语法:for month from 1 to 12 increment 1
--还可以使用子查询:for year in (select year from t603)