oracle求年平均值,求一句SQL,分组计算平均值

本文详细解析了CTE(Common Table Expression)在SQL中的使用,通过实际例子展示如何利用with子句进行多阶段查询和动态分组,涉及row_number(), union all和复杂条件的案例分析。
摘要由CSDN通过智能技术生成

CTE的等价写法:

SQL> with d as

2  (

3  select 1 as seq,1 as status,1 as v from dual union all

4  select 2,1,2 from dual union all

5  select 3,1,3 from dual union all

6  select 4,1,4 from dual union all

7  select 5,2,5 from dual union all

8  select 6,2,7 from dual union all

9  select 7,2,9 from dual union all

10  select 8,1,11 from dual union all

11  select 9,1,12 from dual union all

12  select 10,2,13 from dual union all

13  select 11,2,14 from dual union all

14  select 12,2,15 from dual union all

15  select 13,2,16 from dual

16  ),

17  s as (select row_number() over(order by seq) as rn,seq,status,v from d),

18  t (rn,seq,status,v,g) as (select rn,

19                                seq,

20                                status,

21                                v,

22                                1 g

23                           from s

24                          where rn = 1

25                          union all

26                         select t.rn + 1,

27                                s.seq,

28                                s.status,

29                                s.v,

30                                case when s.status = t.status then t.g else t.g + 1 end

31                           from t,s

32                          where t.rn = s.rn -1)

33  select max(seq) seq,max(status) status,avg(v) avg_v from t group by g order by g

34  /

SEQ     STATUS      AVG_V

---------- ---------- ----------

4          1        2.5

7          2          7

9          1       11.5

13          2       14.5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值