Return min(DATE) 如果日期不存在

Return min(DATE) if Date does not exist

在 Oracle SQLDeveloper 中,我正在尝试 运行 一个查询,我发现 return 一个特定日期作为开始日期,但是 return 最小日期,如果最早的现有日期是大于指定的开始日期。我尝试使用 CASE 语句执行此操作,但我不断收到 "missing right parentheses" 错误。到目前为止,这是我的代码:

select 
  a.program
  , a.match_file
  , (case when b.date = '27-JAN-13' then b.date else min(b.date end)) as Startdate
from Schema1.program a, Schema1.detail b
where a.match_file = b.matchfile
  and (case when b.date=' ' then min(b.date) else b.date end) = '27-JAN-13'
  group by a.program, a.match_file
;

如果我做错了,有人可以告诉我吗?我也尝试过使用 IF 语句和几个不同的 UNION 语句,但我无法达到我想要的 return。

您可能需要考虑 COALESCE 函数(选择第一个非空参数)。但是,如果您过滤的是空白而不是空值,这可能不起作用。在这种情况下,CASE 语句应该适合您的需要。

在您的代码中,第一个 case 语句中的 "end" 位于 min() 内部,这可能就是您收到错误的原因。

, (case when b.date = '27-JAN-13' then b.date else min(b.date) end) as Startdate

我无法弄清楚您要做什么,但根据您的描述,我得出了以下 sql。我认为您不需要在 where 子句中进行任何过滤,因为您需要每一行结果。您只想知道每个 program/file 组合的最早日期是否在 1 月 27 日之后。 select 中的 case 语句负责处理此问题。

"return a specific date as the StartDate, but return the minimum date if the earliest existing date is greater than the specified start date"

select 
    a.program
    , a.match_file
    , case when min(b.date) > '27-JAN-13' then min(b.date) else '27-JAN-13' end as Startdate
from Schema1.program a, Schema1.detail b
where a.match_file = b.matchfile
group by a.program, a.match_file;

您的陈述在语法上不正确。 将 end 移动到最小聚合之外,如下所示

select 
  a.program
  , a.match_file
  , (case when b.date = '27-JAN-13' then b.date else min(b.date) end) as Startdate
from Schema1.program a, Schema1.detail b
where a.match_file = b.matchfile
  and (case when b.date=' ' then min(b.date) else b.date end) = '27-JAN-13'
  group by a.program, a.match_file
;