|
代码要改改了, 具体如下:
SQL> select * from test1;
ID DATES A
-------------------------------- ----------- ----------
50201281 2015/1/1 1
50201281 2015/1/2 2
50201281 2015/1/3 3
50201281 2015/1/11 4
50201281 2015/1/12 5
50201281 2015/1/13 6
50201281 2015/1/22 7
50201281 2015/1/23 8
50201281 2015/1/24 9
50201282 2011/1/1 10
50201282 2011/1/2 11
50201282 2011/1/3 12
12 rows selected
SQL>
SQL> with t1 as
2 (
3 select id,
4 years,
5 months,
6 decode(grp, '01', 4, rn_flag) rn_flag,
7 sum_a
8 from (select id,
9 years,
10 months,
11 rn_flag,
12 sum(sum_a) sum_a,
13 grouping(id) || grouping(rn_flag) grp,
14 count(*) cnt
15 from (SELECT id,
16 to_char(dates, 'yyyy') years,
17 to_char(dates, 'mm') months,
18 decode(trunc((to_number(to_char(dates, 'dd')) - 1) / 10),
19 0,
20 '1',
21 1,
22 '2',
23 '3') rn_flag,
24 sum(A) sum_a
25 FROM test1
26 group by id,
27 decode(trunc((to_number(to_char(dates, 'dd')) - 1) / 10),
28 0,
29 '1',
30 1,
31 '2',
32 '3'),
33 to_char(dates, 'yyyy'),
34 to_char(dates, 'mm')
35 order by 1, 2, 3, 4)
36 group by rollup((id, years, months), rn_flag)
37 having grouping(id) <> 1)
38 where grp = '00'
39 or (grp = '01' and cnt > 1)
40 ),
41 t2 as
42 (
43 select a2.id,
44 a2.years,
45 a2.months,
46 a1.rn
47 from (select level rn from dual connect by level <= 4) a1,
48 (select id,
49 to_char(dates, 'yyyy') years,
50 to_char(dates, 'mm') months
51 from test1
52 group by id, to_char(dates, 'yyyy'), to_char(dates, 'mm')) a2
53 )
54 select t2.id 序号,
55 t2.years 年,
56 t2.months 月,
57 t2.rn 旬月标示,
58 decode(t2.rn, 4, sum(decode(t2.rn, 4, 0, nvl(t1.sum_a, 0))) over(partition by t2.id, t2.years, t2.months), nvl(t1.sum_a, 0)) 累计A值
59 from t1, t2
60 where t1.id(+) = t2.id
61 and t1.years(+) = t2.years
62 and t1.months(+) = t2.months
63 and t1.rn_flag(+) = t2.rn
64 order by 1, 2, 3, 4
65 /
序号 年 月 旬月标示 累计A值
-------------------------------- ---- -- ---------- ----------
50201281 2015 01 1 6
50201281 2015 01 2 15
50201281 2015 01 3 24
50201281 2015 01 4 45
50201282 2011 01 1 33
50201282 2011 01 2 0
50201282 2011 01 3 0
50201282 2011 01 4 33
8 rows selected
|
|