如何在SAS中的两个日期之间计算每年的月数

时间:2017-01-13 22:18:22

标签: sas

一个快速的SAS问题,我有一个像这样的数据集:

   Case | Start_date |  End_date 
    001 |    2014/12 |   2016/01
    002 |    2013/10 |   2015/12
    ...

根据Start_date和End_date,我想获得两个日期之间每年的月数。

   Case | Start_date |  End_date | 2012 | 2013 | 2014 | 2015 | 2016
    001 |    2014/12 |   2016/01 |   0  |   0  |   1  |  12  |  1
    002 |    2013/10 |   2015/12 |   0  |   3  |  12  |  12  |  0
    ...

SAS的任何想法?

请帮助提供解决方案。

最佳

2 个答案:

答案 0 :(得分:1)

试试这个。我做了一些简化的假设,包括使用字符输入数据。这应该适用于任意年限。

data have;
    case="001"; start="2012/12"; end="2016/01"; output;
    case="002"; start="2013/10"; end="2015/12"; output;
run;

* Sorting is necessary for the PROC TRANSPOSE later.;
proc sort data=have;
    by case start end;
run;

data two;
    set have;

    * For each date range, extract the starting and ending
    * year and month.;
    startyear=input(substr(start,1,4),4.0);
    startmonth=input(substr(start,6,2),2.0);
    endyear=input(substr(end,1,4),4.0);
    endmonth=input(substr(end,6,2),2.0);

    * For each year in range, calculate the number of months.;
    do year=startyear to endyear;
        months=0;
        * Start with the month of the first year or January.;
        if year=startyear then mstart=startmonth;
         else mstart=1;
        * End with the month of the last year or December.;
        if year=endyear then mstop=endmonth;
         else mstop=12;

        * Calculate the number of months in the year.;
        months=mstop-mstart+1;

        * Create a row for each year in the range.;
        output;

    end;

    keep case start end year months;
run;

* Transpose the data to create a variable for each year 
* used in any range.;
proc transpose data=two out=want;
    by case start end;
    id year;
run;

答案 1 :(得分:0)

SAS具有相对容易处理日期的功能。此示例使用INTNX定义每年的范围,使用INTCK计算从开始到结束的月份。

      "scripts": [
    "../node_modules/gsap/src/minified/TweenMax.min.js",
    "../node_modules/scrollmagic/scrollmagic/minified/ScrollMagic.min.js",
    "../node_modules/scrollmagic/scrollmagic/minified/plugins/animation.gsap.min.js",
    "../node_modules/scrollmagic/scrollmagic/minified/plugins/debug.addIndicators.min.js"
  ],

enter image description here