日期范围的Oracle End Of Month值

时间:2016-11-29 02:33:54

标签: sql oracle date plsql

Oracle有一个last_day()函数:

SELECT LAST_DAY(to_date('01/01/2016','DD/MM/YYYY')) from dual;

结果:

31/01/2016

如何获取日期范围中的EndOfMonths列表以在WHERE子句中使用,目前我使用的是大字符串,并且它不直观或未来证明,例如:

SELECT * FROM Balances
WHERE TheDate IN
('31/Jan/2016','29/Feb/2016', '31/Mar/2016','30/Apr/2016', '31/May/2016','30/Jun/2016', '31/Jul/2016','31/Aug/2016',
'30/Sep/2016', '31/Oct/2016','30/Nov/2016')

我更喜欢使用函数来插入开始日期和结束日期。

2 个答案:

答案 0 :(得分:1)

尝试这样的事情来生成月份的最后一天:

List<List<List<String>>> seqNew = new ArrayList<List<List<String>>>();
seqNew.add(sequences);
JavaRDD<List<List<String>>> rdd =  sc.parallelize(seqNew);

将10改为您需要的#个月。假设&#34; TheDate&#34;是一个适当的oracle DATE类型。如果需要,使用to_char换行格式化为字符串。

使用@JeremyThompsons Months_Bet之间的建议:

SELECT LAST_DAY(add_months(to_date('01/01/2016','DD/MM/YYYY'), level) )
from dual
CONNECT BY LEVEL <= 10

使用@mathguys函数顺序建议的最终查询:

SELECT LAST_DAY(add_months(to_date('01-01-1991','DD/MM/YYYY'), level) )
from dual
CONNECT BY LEVEL <=
(SELECT MONTHS_BETWEEN 
   (TO_DATE('02-02-1999','MM-DD-YYYY'),
    TO_DATE('01-01-1991','MM-DD-YYYY') ) "Months"
    FROM dual);

还有一个@mathguys优化,不需要标量子查询:

SELECT * FROM Balances b
WHERE TheDate IN
(SELECT add_months(LAST_DAY(to_date('28/Feb/2015','DD-MM-YYYY')), level) 
from dual
CONNECT BY LEVEL <=
(SELECT MONTHS_BETWEEN 
   (TO_DATE('30/Nov/2016','DD-MM-YYYY'),
    TO_DATE('28/Feb/2015','DD-MM-YYYY') ) "Months"
    FROM dual));

答案 1 :(得分:0)

您可以创建如下所示的函数,该函数将返回所有月份的月末:

create or replace function getEndOfMonths return varchar2 as
    cnt number;
    current_year varchar2(5);
    end_of_months varchar2(180) := '';
    end_of_month varchar2(13);
begin
    select to_char(sysdate,'YYYY') into current_year from dual;
    for cnt in 1..12 loop
        SELECT LAST_DAY(to_date('01/'||cnt||'/'||current_year,'DD/MM/YYYY')) into end_of_month from dual;
        end_of_months := end_of_months||','||end_of_month;
    end loop;
    return substr(end_of_months,2);
end;
/

<强>更新 以下是基于月份范围:

create or replace function getEndOfMonths(start_month number, end_month number) return varchar2 as
    cnt number;
    current_year varchar2(5);
    end_of_months varchar2(180) := '';
    end_of_month varchar2(13);
begin
    select to_char(sysdate,'YYYY') into current_year from dual;
    for cnt in start_month..end_month loop
        SELECT LAST_DAY(to_date('01/'||cnt||'/'||current_year,'DD/MM/YYYY')) into end_of_month from dual;
        end_of_months := end_of_months||','||end_of_month;
    end loop;
    return substr(end_of_months,2);
end;
/