比较日期范围(按月(整数)和年(整数)

时间:2020-09-30 22:11:34

标签: java sql oracle datetime outsystems

比较日期范围时遇到问题。我必须验证特定月份和年份内的日期。月和年是整数值。

注意:我正在通过Oracle数据库使用OUTSYSTEMS聚合

两个查询结果的示例:

    Start Date    End Date 
1   2020-08-16    2020-10-14
2   2019-11-01    2020-08-15

案例1

输入:

Month = 9
Year = 2020

预期结果:

    Start Date    End Date 
1   2020-08-16    2020-10-14

案例2

输入:

Month = 8
Year = 2020

预期结果:

    Start Date    End Date 
1   2020-08-16    2020-10-14
2   2019-11-01    2020-08-15

案例3

输入:

Month = 3
Year = 2020

预期结果:

    Start Date    End Date 
2   2019-11-01    2020-08-15

案例4

输入:

Month = 10
Year = 2019

预期结果:无行

以Java方式进行选择。我正在使用Month()和Year()之类的系统函数将行转换为整数。

((Month(StartDate) <= Month and Month(EndDate) = Month)
and
(Year(StartDate) <= Year and Year(EndDate) = Year))
or
((Month(StartDate) <= Month and Month(EndDate) = Month)
and
(Year(StartDate) <= Year and Year(EndDate) = Year))

上面的代码不起作用。我尝试了许多组合但均未成功。我没有特殊的比较功能。为了进行分析,我创建了四个方案来带出我正在研究的月份和年份中包含的日期。但是我没有使代码起作用。有人可以为我开路

3 个答案:

答案 0 :(得分:3)

一种简单的方法使用算术:

where year * 100 + month 
    between year(startdate) * 100 + month(startdate)
        and year(enddate)   * 100 + month(enddate)

但是,这可能不是最有效的方法。通常,您要避免在要过滤的列上应用函数。更好的选择是将year / month参数转换为日期-不幸的是,您没有标记数据库,并且date函数是特定于供应商的,因此实际上不可能提出建议。

如果您不想between

where year * 100 + month >= year(startdate) * 100 + month(startdate)
  and year * 100 + month <= year(enddate)   * 100 + month(enddate)

答案 1 :(得分:1)

这有效吗?考虑您输入的月份的 m 和年份的 y

StartDate <= AddDays(AddMonths(NewDate(Year(y), Month(m), 1),1)-1)
and
EndDate >= NewDate(Year(y), Month(m), 1))

这种想法就像:按所有低于输入月份的最后一天的开始日期和所有大于输入月份的第一天的结束日期进行过滤。

关于性能,使用这种方法,您不必对要过滤的列进行任何逻辑/过滤。

答案 2 :(得分:1)

与供应商无关的解决方案

GMB的回答很好,如果是我,我可能会同意。正如GMB所说,它是特定于供应商的,因为日期功能是。如果您想要一个适用于所有数据库供应商的解决方案,请使用Java进行日期数学计算,以便只需要在数据库中进行简单的日期比较。

    int month = 8;
    int year = 2020;

    YearMonth ym = YearMonth.of(year, month);
    LocalDate monthStart = ym.atDay(1);
    LocalDate monthEnd = ym.atEndOfMonth();

将这些日期传递给查询时,可以简单地输入搜索条件:

  where startDate <= monthEnd and endDate >= monthStart
相关问题