简体   繁体   中英

Oracle query displays data by month and year

I want to display the amount of data by month and year. This is an example of displaying data by date:

select count(*) from db.trx where trxdate = to_date('2018-04-23','yyyy-mm-dd')

When I try to display the amount of data by month and year, no query results appear. Is there something wrong with the query?

The query:

select count(*) from db.trx where trxdate = to_date('2018-04','yyyy-mm')

You need to apply the function to trxdate . Using your logic:

SELECT Count(*) 
FROM   olap.trxh2hpdam 
WHERE  To_char(trxdate, 'YYYY-MM') = '2018-04'; 

However, I strongly recommend that you use direct date comparisons:

WHERE trxdate >= date '2018-04-01' 
AND 
trxdate < date '2018-05-01'

This will allow the database to use an index on trxdate .

There are a couple of ways of accomplishing what you're trying to do. Which one works for you will depend on your database design (for example, the indexes you've created). One way might be this:

SELECT COUNT(*) FROM olap.trxh2hpdam
 WHERE TRUNC(trxdate, 'MONTH') = DATE'2018-04-01';

This will round the date down to the first of the month (and, of course, remove any time portion). Then you simply compare it to the first of the month for which you want the data. However, unless you have an index on TRUNC(trxdate, 'MONTH') , this may not be the best course of action; if trxdate is indexed, you'll want to use:

SELECT COUNT(*) FROM olap.trxh2hpdam
 WHERE trxdate >= DATE'2018-04-01'
   AND trxdate < DATE'2018-05-01';

There are a number of functions at your disposal in Oracle (eg ADD_MONTHS() ) in the event that the date you use in your query is supposed to be dynamic rather than static.

Just FYI, there is no reason not to use ANSI date literals when trying to retrieve data by day as well. I'm not sure your original query is a good example of getting data for a particular day, since the Oracle DATE datatype does at least potentially include a time:

SELECT COUNT(*) FROM olap.trxh2hpdam
 WHERE trxdate >= DATE'2018-04-23'
   AND trxdate < DATE'2018-04-24';

or:

SELECT COUNT(*) FROM olap.trxh2hpdam
 WHERE TRUNC(trxdate) = DATE'2018-04-23';

EDIT

In case the month and year are dynamic, I would build a date from them (eg, TO_DATE('<year>-<month>-01', 'YYYY-MM-DD') ) and then use the following query:

SELECT COUNT(*) FROM olap.trxh2hpdam
 WHERE trxdate >= TO_DATE('<year>-<month>-01', 'YYYY-MM-DD')
   AND trxdate < ADD_MONTHS( TO_DATE('<year>-<month>-01', 'YYYY-MM-DD'), 1 );

Hope this helps.

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