想要获得过去30天的总和

时间:2015-07-17 06:50:10

标签: sql oracle

以下是我为获取记录而编写的代码

SELECT run_time, SUM(rec_cnt) reg_cnt FROM(
select run_time,rec_cnt from
(select TO_DATE(TO_CHAR(LST_UPDT_TIME,'DD-MON-YYYY'),'DD-MON-YYYY') run_time,max(Running_Total) rec_cnt from (
SELECT
    LST_UPDT_TIME,
    (
     SELECT COUNT(*)
     FROM DM_REG_SMRY T2
     WHERE T2.LST_UPDT_TIME <= T1.LST_UPDT_TIME AND REG_STS_ID = 14
    ) AS Running_Total
FROM
    DM_REG_SMRY T1
    order by T1.LST_UPDT_TIME
    )
    group by TO_DATE(TO_CHAR(LST_UPDT_TIME,'DD-MON-YYYY'),'DD-MON-YYYY')
    order by TO_DATE(TO_CHAR(LST_UPDT_TIME,'DD-MON-YYYY'),'DD-MON-YYYY')
    )
    UNION
(SELECT TRUNC(SYSDATE+1 - ROWNUM) run_time , 0 as rec_cnt FROM DUAL CONNECT BY ROWNUM <= 30)
)GROUP BY run_time
ORDER BY run_time;

我得到了以下输出

18-06-2015 00:00    6
19-06-2015 00:00    7
20-06-2015 00:00    0
21-06-2015 00:00    0
22-06-2015 00:00    0
23-06-2015 00:00    0
24-06-2015 00:00    12
25-06-2015 00:00    0
26-06-2015 00:00    0
27-06-2015 00:00    0
28-06-2015 00:00    0
29-06-2015 00:00    0
30-06-2015 00:00    0
01-07-2015 00:00    0
02-07-2015 00:00    0
03-07-2015 00:00    49
04-07-2015 00:00    0
05-07-2015 00:00    0
06-07-2015 00:00    0
07-07-2015 00:00    0
08-07-2015 00:00    0
09-07-2015 00:00    0
10-07-2015 00:00    49
11-07-2015 00:00    0
12-07-2015 00:00    0
13-07-2015 00:00    65
14-07-2015 00:00    77
15-07-2015 00:00    101
16-07-2015 00:00    0
17-07-2015 00:00    0

但是我想要为零位重复最后一个非零值

请帮忙

1 个答案:

答案 0 :(得分:0)

我不是百分百确定,但如果我理解正确,您想要计算过去30天累积的DM_REG_SMRY行数(从SYSDATE-(30-1)开始到今天结束{ {1}})和SYSDATE-(1-1)。并且您希望按日期获得累计计数。

这意味着,如果您使用REG_STS_ID=14DM_REG_SMRY):

REG_STS_ID=14

你真的想要这个结果:

 6 rows on 18-06-2015
 1 row  on 19-06-2015 
 5 rows on 24-06-2015 
37 rows on 03-07-2016
16 rows on 13-07-2015 
12 rows on 14-07-2015
24 rows on 15-07-2015

如果这是您真正想要的,那么可能的解决方案是:

18-06-2015 00:00    6
19-06-2015 00:00    7
20-06-2015 00:00    7
21-06-2015 00:00    7
22-06-2015 00:00    7
23-06-2015 00:00    7
24-06-2015 00:00    12
25-06-2015 00:00    12
26-06-2015 00:00    12
27-06-2015 00:00    12
28-06-2015 00:00    12
29-06-2015 00:00    12
30-06-2015 00:00    12
01-07-2015 00:00    12
02-07-2015 00:00    12
03-07-2015 00:00    49
04-07-2015 00:00    49
05-07-2015 00:00    49
06-07-2015 00:00    49
07-07-2015 00:00    49
08-07-2015 00:00    49
09-07-2015 00:00    49
10-07-2015 00:00    49
11-07-2015 00:00    49
12-07-2015 00:00    49
13-07-2015 00:00    65
14-07-2015 00:00    77
15-07-2015 00:00    101
16-07-2015 00:00    101
17-07-2015 00:00    101