简体   繁体   中英

How to to count numbers in consecutive month in SQL oracle

I am learning advance sql in oracle. I want to find the count of numbers in two consecutive month. In normal sql my result could be produced like this way

select count(distinct number) 
from table1 
where date='1-sep-21' 
and number in (select distinct number 
               from table2 
               where date = '1-aug-21')

So these numbers from September are also found in August. What I want to get the result like

Month   count_number(current_month but also in previous month)
08-2021         122377 
09-2021          40000 
10-2021.          230

I am working in Oracle SQL. How can I achieve this? Kindly help me to get the idea.

Your WHERE clause has three problems:

where date='1-sep-21'

First, 'date' is a reserved word, so your column should not be named that. Since you specified that in lower-case and without double-quotes, it would actually be considered case-insenstive and thus collide with the reserved word 'DATE', so I mus assume that is not really the name of the column.

Second, assuming your column is - as it should be - of type DATE, then you are comparing a DATE with the character string '1-sep-21'. This will force an implied TO_DATE to convert that string to a DATE and may or may not throw an error, depending on the setting of NLS_DATE_FORMAT. Bottom line, you should never rely on implied conversions.

Third, you only specify 2 digits for the year of your 'date'. C'mon, man. In 1998-1999, I and millions of my colleagues spent way too much of our time remediating Y2k. And now you try to recreate the problem.

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