简体   繁体   中英

I want to generate a report monthly

--query--

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

--Result--

Count(*)
72

Currently I am using a monitoring tool that automatically run every day and gets the total count for whole day. Now I want to run a query that will automatically count the data for the whole month without changing the query every month.

A condition you use:

and createdDatetime >= trunc(sysdate);

returns data for today , as TRUNC , applied to SYSDATE , gives "very first moments of today".

But, if you adjust it a little bit and truncate SYSDATE to a month, you'd get the first day of current month, eg

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>

so you'd, finally, use

and createdDatetime >= trunc(sysdate, 'mm')

Depends on what you prefer by telling "the whole month" ;

The period past since one-month before :

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

From the beginning of the current month :

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

SQL Fiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM