我想每月生成一个报告

时间:2018-07-23 07:17:36

标签: sql oracle

-查询-

select count(*)
    from TOKEN
    where CODE = xxx
      and createdDatetime >=trunc(sysdate);

-结果-

Count(*)
72

当前,我正在使用一个监视工具,该工具每天自动运行并获得一整天的总数。现在,我想运行一个查询,该查询将自动计算整个月的数据,而无需每月更改查询。

2 个答案:

答案 0 :(得分:0)

您使用的条件:

and createdDatetime >= trunc(sysdate);

返回今天 的数据,因为应用于TRUNC的{​​{1}}给出了“今天非常重要的时刻”。

但是,如果您稍加调整并将SYSDATE截短到一个月,则会得到当前月份的第一天,例如

SYSDATE

所以您最终会使用

SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> select
  2    trunc(sysdate) today,
  3    trunc(sysdate, 'mm') this_month
  4  from dual;

TODAY               THIS_MONTH
------------------- -------------------
23.07.2018 00:00:00 01.07.2018 00:00:00

SQL>

答案 1 :(得分:0)

通过告诉“整个月”取决于您的喜好;

从一个月前开始过去的时间:

 select count(1)
   from TOKEN
  where CODE = 'xxx'
    and months_between(trunc(sysdate),createdDatetime)<=1;

从本月初开始:

 select count(1)
   from TOKEN
  where CODE = 'xxx'
    and to_char(createdDatetime,'yyyymm') = to_char(trunc(sysdate),'yyyymm');

SQL Fiddle Demo

相关问题