Domanda

I have to extract some data from a table every month based on a date column. The table gets some new records every month and I have to write an query using which I can get records added in the previous month.

Query is

   select r.iar_start_date
from reps r
where
case when (extract(month from sysdate) = 1)
  then ((extract(month from r.iar_start_date) = 12) and extract(year from r.iar_start_date) = (extract(year from sysdate) - 1))
  else (extract(month from r.iar_start_date) = (extract(month from sysdate) - 1)  and extract(year from r.iar_start_date) = extract(year from sysdate))
end

This query is giving ORA:00907: missing right parenthesis error.

Any help would be highly appreciable.

È stato utile?

Soluzione 2

You cannot have a conditional where clause like that. You'll need to restructure the clause so that it's a single conditional.

Maybe something like:

where
(
  extract(month from sysdate) = 1
  and
  extract(month from r.iar_start_date) = 12
  and
  extract(year from r.iar_start_date) = extract(year from sysdate) - 1
)
or
(
  extract(month from sysdate) <> 1
  and
  extract(month from r.iar_start_date) = extract(month from sysdate) - 1
  and
  extract(year from r.iar_start_date) = extract(year from sysdate)
)

Altri suggerimenti

If what you want are rows for last month then you can employ some standard date manipulation tricks to achieve a much simpler condition:

where r.iar_start_date between trunc(add_months(sysdate,-1), 'MM') 
                       and trunc(sysdate, 'MM') - (1/86400)

ADD_MONTHS() is an Oracle built-in function for adding months; using a negative offset subtracts months.

TRUNC() with the 'MM' mask gives the first day of the month, at midnight.

We can also adjust the date with simple arithmetic. - (1/86400) subtracts one second from the day, in this case yielding the maximum datetime value for the previous day.

select r.iar_start_date
from reps r
where
1 = case 
      when (extract(month from sysdate) = 1)
      and  ((extract(month from r.iar_start_date) = 12) and extract(year from r.iar_start_date) = (extract(year from sysdate) - 1))
       then 1
      when (extract(month from r.iar_start_date) = (extract(month from sysdate) - 1)  
      and extract(year from r.iar_start_date) = extract(year from sysdate))
      then 1
      else 0
     end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top