In BI report development, often need to calculate the year-end, need to use the month-end date, with the date function of the database system needs to be in each place to use the date to write the function, in some special cases, the function will be very complex, even can not achieve the desired results.
For example, in Teradata, the Addmonths function calculates only the month:
Date |
Increment value |
Results |
2015/01/01 |
1 |
2015/02/01 |
2015/01/31 |
1 |
2015/02/28 |
2015/02/28 |
-1 |
2015/01/28 |
2015/03/31 |
-1 |
2015/02/28 |
2015/02/28 |
0 |
2015/02/28 |
As the table shows, at the end of the month, you can not count the entire month of information, often not the desired results.
It is therefore necessary to add variables to the job to achieve monthly data at the end of the month.
Perl implementation is as follows, simple test, production environment before the launch, please use sprintf format.
#!/usr/bin/perl# Get month End Date # liangwl# 2015/9/18Subadd_delta_month{my($date,$cnt) =@_; my$year=int($date/10000); my$month=int($date/ -)% -+$cnt-1; my$yyyymm= ($year+ Floor ($month/ A)) * -+$month% A+1; my@mmdd; Push@mmdd, QW (0131),(int($yyyymm/ -)%4==0?"0229":"0228"), QW (033104300531 0630073108310930103111301231); returnint($yyyymm/ -).$MMDD[($yyyymm% --1)% A];} Subfloor{my($i) =@_; return$i>=int($i) ?int($i) :int($i) -1;} PrintAdd_delta_month (20150131,- -)."\ n";PrintAdd_delta_month (20150131,- -)."\ n";PrintAdd_delta_month (20150131,- A)."\ n";PrintAdd_delta_month (20150131,0)."\ n";PrintAdd_delta_month (20150131,1)."\ n";PrintAdd_delta_month (20150131, One)."\ n";PrintAdd_delta_month (20150131, A)."\ n";PrintAdd_delta_month (20150131, -)."\ n";
Application scenario: "Last six months statistics", "Change by Chain", "Change year-over", "X quarter YoY" and so on
Perl Gets the end of any month before and after