我必须每月根据日期列从表中提取一些数据。该表每月都会获得一些新记录,我必须编写一个查询,使用该查询可以获得上个月添加的记录。
查询
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
此查询出现ORA:00907: missing right parenthesis
错误。
任何帮助都会非常值得注意。
答案 0 :(得分:2)
如果您想要的是上个月的行,那么您可以使用一些标准的日期操作技巧来实现更简单的条件:
where r.iar_start_date between trunc(add_months(sysdate,-1), 'MM')
and trunc(sysdate, 'MM') - (1/86400)
ADD_MONTHS()an Oracle built-in function用于添加月份;使用负偏移减去几个月。
带有'MM'面具的TRUNC()给出了该月的第一天,午夜。我们也可以通过简单的算术调整日期。 - (1/86400)
从当天减去一秒,在这种情况下产生前一天的最大日期时间值。
答案 1 :(得分:1)
你不能有这样的条件where
条款。您需要重新构造该子句,使其成为单个条件。
可能是这样的:
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)
)
答案 2 :(得分:1)
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