基于会计年度的日期拆分

时间:2010-01-30 11:44:21

标签: sql database postgresql

鉴于从日期到日期会计年度系统,我希望获得所有分割期限 来自&基于财政年度制度的日期。下面用例子说明:

示例1: 财政年度制度:4月至3月

日期:2008年1月5日 迄今为止:2008年5月15日

根据财政年度制度,持续时间应分为:

Jan-05-2008 to Mar-31-2008
Apr-01-2008 to May-15-2008

示例2: 财政年度制度:4月至3月

日期:2008年1月17日 迄今为止:2009年5月20日

根据财政年度制度,持续时间应分为:

Jan-17-2008 to Mar-31-2008
Apr-01-2008 to Mar-31-2009
Apr-01-2009 to May-20-2009

我正在寻找方法/算法来解决PostgreSQL 8.2中的问题。

此致

Gnanam

3 个答案:

答案 0 :(得分:1)

您可以创建一个包含所有会计年度的开始和结束的表格,例如

Periods (PeriodStartDt, PeriodEndDt)

如果这些表至少部分重叠,那么您可以join在一起。使用case语句选择句点的结尾或行的结尾,具体取决于稍后的结尾。例如(未测试):

select      case when yt.StartDt < p.PeriodStartDt then p.PeriodStartDt
                 else yt.StartDt
            end as SplitStart
,           case when yt.EndDt > p.PeriodEndDt then p.PeriodEndDt
                 else yt.EndDt
            end as SplitEnd
,           yt.*
from        YourTable yt
inner join  Periods p
on          yt.StartDt < p.PeriodEndDate
            and yt.EndDt >= p.PeriodStartDate

答案 1 :(得分:1)

我实际上更喜欢Andomar的解决方案(添加了一个自动填充Periods表的流程),但为了好玩,这里有一个不需要它的解决方案。

CREATE TABLE your_table (start_date date, end_date date);
INSERT INTO your_table VALUES ('Jan-17-2008', 'May-20-2009');

SELECT
    GREATEST(start_date, ('04-01-'||series.year)::date) AS year_start,
    LEAST(end_date, ('03-31-'||series.year + 1)::date) AS year_end
FROM
    (SELECT
        start_date,
        end_date,
        generate_series(
            date_part('year', your_table.start_date - INTERVAL '3 months')::int,
            date_part('year', your_table.end_date - INTERVAL '3 months')::int)
    FROM your_table) AS series(start_date, end_date, year)
ORDER BY
    start_date;

答案 2 :(得分:0)

CREATE TABLE your_table (start_date date, end_date date); 
INSERT INTO your_table VALUES (CONVERT (date, GETDATE()),CONVERT (date, DATEADD(year, -1, GETDATE())) ); 

WITH mycte AS
 (
 SELECT 1 as id
 UNION ALL
 SELECT id + 1
 FROM mycte
 WHERE id + 1 < = 12
 ),
 cte_distribution as
 (
 SELECT *, 
 DATEPART (month,DATEADD(month, mycte.id - 1, your_table.start_date)) as month_number ,
 DATEPART (YEAR,DATEADD(month, mycte.id - 1, your_table.start_date)) as  cal_year,
 12000/12 as cash
 FROM your_table
 CROSS JOIN mycte
 )
 select 
 *,
 (CASE WHEN month_number between 1 and 3 THEN '1st quarter' WHEN month_number between 4 and 6 THEN '2nd quarter'  WHEN month_number between 7 and 9 THEN '3rd quarter' WHEN month_number between 9 and 12 THEN '4th quarter' END) as Quarter,
 CASE WHEN month_number between 1 and 6 THEN  CAST(CAST((cal_year - 1) as CHAR(4)) + '-' + CAST(cal_year as CHAR(4)) AS CHAR(9))  WHEN  month_number between 6 and 12 THEN CAST(CAST((cal_year) as CHAR(4)) + '-' + CAST((cal_year + 1) as CHAR(4)) AS CHAR(9))  ELSE NULL END as fin_year
 from cte_distribution;