How do i calculate the dates in this scenario

I have a situation here and i am not able to think through it
there are 4 date columns in a table and i need to do something like below
First Record start date is the start date, and end date is the next start date -1
Next start date is next start date, and end date is the first end date of the record set of the end dates
Next start date pervious end date + 1 and end date is the current end date
Next start date is the current date and next end date is the current end date
for example lets say we have a table like below
CustomerID CustomerType CustomerEffDt   CustomerTrmDt CustNationalBgnDt CustNationalEndDt
1                  National           2013-08-05        9999-12-31      
2010-11-08            2011-11-02
Now my question is, we would have to calculate the customer effective start and begin dates and national begin and end dates based on the above criteria
we would have to create 4 rows based on the above scenario
I am going mad and not able to think through this
Can somebody help me
Thanks

Declare @Example table (CustomerID int, CustomerEffDt date, CustomerTrmDt date, CustNationalBgnDt date, CustNationalEndDt date, otherstuff varchar(99))
insert @Example Select 1, '3/19/2014', '9999-12-31', '3/19/2015', '2/19/2016', 'first'
UNION Select 2, '3/19/2014', '9999-12-31', '4/19/2014', '5/28/2014', 'second'
UNION Select 3, '2013-08-05', '9999-12-31', '2010-11-08', '2011-11-02', 'first example by OP'
Select CustomerID,Num
, case When Num = 1 Then '1/1/1900'
when NUM = 2 then CustNationalBgnDt
when NUM = 3 then DateAdd(day, 1, CustNationalEndDt )
when NUM = 4 then CustomerEffDt End as startdate
, case When NUM = 1 then DateAdd(day, -1, CustNationalBgnDt)
when NUM = 2 then CustNationalEndDt
when NUM = 3 then Dateadd(Day, -1, CustomerEffDt)
when NUM = 4 then CustomerTrmDt End as EndDate
From @EXAMPLE
Cross Apply (Select 1 as Num UNION Select 2 UNION Select 3 UNION Select 4) as Numbers
order by CustomerID, Num
/* --Your result
1 1 1900-01-01 2015-03-18
1 2 2015-03-19 2016-02-19
1 3 2016-02-20 2014-03-18
1 4 2014-03-19 9999-12-31
2 1 1900-01-01 2014-04-18
2 2 2014-04-19 2014-05-28
2 3 2014-05-29 2014-03-18 ---***
2 4 2014-03-19 9999-12-31 --****
3 1 1900-01-01 2010-11-07
3 2 2010-11-08 2011-11-02
3 3 2011-11-03 2013-08-04
3 4 2013-08-05 9999-12-31
CustomerID StartDate EndDate
1 1900-01-01 2014-03-18
1 2014-03-19 2015-03-18
1 2015-03-19 2016-02-19
1 2016-02-20 9999-12-31
2 1900-01-01 2014-03-18
2 2014-03-19 2014-04-18
2 2014-04-19 2014-05-28
2 2014-05-29 9999-12-31
3 1900-01-01 2010-11-07
3 2010-11-08 2011-11-02
3 2011-11-03 2013-08-04
3 2013-08-05 9999-12-31
;with mycte as
select CustomerID, dt,col,row_number() Over(partition by CustomerID Order by dt) rn
,row_number() Over(partition by CustomerID Order by dt DESC) rn2 from @Example
cross apply (
values( CustomerEffDt,'CustomerEffDt'), (CustomerTrmDt,'CustomerTrmDt')
, (CustNationalBgnDt,'CustNationalBgnDt'), (CustNationalEndDt,'CustNationalEndDt'))
d(dt,col)
Select m1.CustomerID,
Case when m1.rn=1 Then '1/1/1900'
When m2.col='CustNationalEndDt' Then dateadd(day,1,m2.dt)
Else m2.dt end as StartDate,
Case
when m1.rn2=1 Then m1.dt
When m1.col='CustNationalEndDt' Then m1.dt
else dateadd(day,-1,m1.dt) End
as EndDate
From mycte m1 LEFT Join mycte m2 on m1.CustomerID=m2.CustomerID AND m1.rn=m2.rn+1
Order by m1.CustomerID, m1.dt

Similar Messages

  • I have a Mac Pro OS 10.7.5 and have a DVD+R disc with files on it, but it ejects the disk after about 10 seconds--what to do?  How can I get the data off this disc?  I can see it has been already burned, so files are on there?

    I have a Mac Pro OS 10.7.5 and have a DVD+R disc with files on it, but it ejects the disk after about 10 seconds--what to do?  How can I get the data off this disc?  I can see it has been already burned, so files are on there?

    Try cleaning the lens and see if that will restore functionality to the DVD drive.  Use a DVD lens cleaning disk, if you have a can of compressed air, shoot some into the slot or wrap a fine microfiber cloth (eyeglasses cleaning cloth)  around a business card and insert it gently inside the slot.
    If no success, make an appointment at an Apple store genius bar and get a free diagnosis from them.
    Ciao.

  • How do I get the data for this one?

    CF 7, SQL Server 2005
    I will try and explain this as clearly as possible, let me
    know if I failed and I will attempt to clear it up.
    The application keeps track of orders as they go through
    phases of production. Lets assume there are two phases of
    production, phase1 and phase2 with 3 statuses in each phase, new,
    open, complete. (depending on the phase an order can be in more
    than one phase at once.)
    There is a phase_log table which is a reference table that
    has a row for every time the order's status changes.
    Lets say the row in the phase_log table looks like this:
    phase_logID | OrderID | PhaseID | StatusID | etc...
    The main page will have a table for each phase, showing a
    list of the orders that currently have rows in the phase_log table
    for that phase. The kicker is, I only want to pull one row (the
    latest status change which will consequently be the highest status
    ID) for each order per phase.
    once I pull the data I guess I can populate a struct or
    array, but I am new to this and I can't figure out how to get the
    query/s I need to get it.
    Any help is appreciated,
    Thanks

    select phase_logid, orderid, phaseid, etc, max(statusid)
    status
    from yourtables
    where whatever
    group by phase_logid, orderid, phaseid, etc

  • How do i get the Date of this moment from the pc?

    Thanks

    System.currentTimeMillis() returns a long.
    or
    new Date() (java.util.Date) returns a Date Object with the current time and date.
    or
    Calendar.getInstance() returns a Calendar Object with the current date and time in there, can be taken out easly enough.

  • SQ02 InfoSet creation how do I see the data ?

    Hello gurus,
    I have created an InfoSet in SQ02 that I need for BW. How do I see the data from this InfoSet in R/3?
    Thanks,
    Ramona

    Hi,
    To see data from the infoset in the tables create SAP query  from SQ01.
    Thanks,
    Vengal Rao.

  • Text on path: How can I calculate the text length?

    Hi
    I have a text on path (spline item). Now I need the length of this text and the length of the spline item.
    I try to calculate the text length using IWaxLine::GetWidth(), but this is always 0.
    - How can I calculate the length of this text?
    - How can I calculate the length of the spline item?
    Thanks
    Hans

    It would be interesting if you could describe the purpose of your "length", but I don't have an answer anyway. Would the bounding box be sufficient?
    Considering that TOP may be combined with arbitrary spline paths, this could become an exercise in higher math. I haven't yet encountered a function that returns the mathematical length of such a spline.
    Otherwise it could be solved if you iterate and sum up the relevant points of the bounding box (ascender, descender, baseline?) of individual glyphs.
    Be warned that the whole TOP looks alien, as if it were a transplant from a different program. Experience also shows that documented and actually used interfaces / commands are completely different animals ...
    Dirk

  • How we calculate the date difference between two list in SharePoint 2010

    Hi friend's....I have two list first is list1. In this list i have two coulmn start_date and End_date. In second list2 i have two column HolidayName and Holiday_date. Now i want two find the number of day in list1 Excluding Weekend and Holiday_date(that
    column from list2). How i will do ..? Please help me dosto..

    Thanks for reply...
    I have done the date difference in list1. But i want to Exclude the Holiday_date form list2.
    I have list1 - Start_date , End_date, Number_of_day(Exclude weekend and Holiday_date between Start_date and End_date )
    list2 - HolidayName, Holiday_date
    Now how i will calculate the Number_of_day in first list.

  • How to generate the date in this format - "24-NOV-2002" ?

    i want to pass the date from java into oracle Date format. I have tried to use the SimpleDateFormat class in java. However, I could only get the following formats:
    1. "dd-mm-yyyy" --> "24-11-2002"
    2. "dd-MM-yyyy" --> "24-11-2002"
    3. "dd-MMM-yyyy" --> "24-NOVEMBER-2002"
    4. "dd-MMMMM-yyyy" --> "24-NOVEMBER-2002"
    How can i get the date format in "24-NOV-2002"?
    Thank you very much.

    3. "dd-MMM-yyyy" --> "24-NOVEMBER-2002"This should have given it to you as 24-Nov-2002 not 24-NOVEMBER-2002.
    If your only problem is the case I'd suggest using String.toUpperCase().
    E.G.
    Date dt = Calendar.getInstance().getTime();
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    System.out.println(fmt.format(dt).toUpperCase());If you are trying to format the date for an SQL statement its a lot easier to use a PreparedStatement and setDate(...).
    Col

  • I wanted to know how do you calculate the number of days between two dates

    i wanted to know how do you calculate the number of days between two dates in java ? i get both the dates from the database. i guess there are many issues like leap year and Febuary having diff no of months ..etc.

    thanks..
    I solve my problem as
    public class MyExample {
        public static void main(String a[]) {
            String stdate = "2009-03-01";
            java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis());
            java.sql.Date preDate = java.sql.Date.valueOf(stdate);
            System.out.println(currentDate);
            System.out.println(preDate);
    //        int dateCom = preDate.compareTo(currentDate);
    //        System.out.println(dateCom);
            long diff = currentDate.getTime() - preDate.getTime();
            int days = (int) Math.floor(diff / (24 * 60 * 60 * 1000));
             System.out.println(days);
    }

  • My iPhone says "o death" where the date should be on the lock screen, why is it doing this and how do I get the date back?

    My iPhone says "o death" where the date should be on the lock screen, why is it doing this and how do I get the date back?

    I tried powering off and on and it went away, but I can't tell if it's been broken into since everything works fine (I'm using it now) is there a test to see if it's been broken into?
    Thanks for all your replies!

  • Hi i lost my iphone on a train station, how can i erase the data or find it . i had this "find my iphone" turned on.

    hi i lost my iphone on a train station, how can i erase the data or find it . i had this "find my iphone" turned on.

    if you have this feature turned on you will see the device listed in the top left corner
    click on it and a pop up will show your options

  • In AP invoice i need to make "Terms date " field to calculate the date automatically when i select the payment terms

    In AP invoice i need to make "Terms date " field to calculate the date automatically when i select the payment terms.
    How can i do this?

    Hi,
    You can select the Payment Term at PO Header Level.
    When you book an invoice, that Payment Term will automatically defaulted to Invoice.
    You can define Payment Term in AP.
    Payment terms have one or more payment terms lines, each of which creates one scheduled payment. Each payment terms line and each corresponding scheduled  payment has a due date or a discount date based on either a specific day of a month, such as the 15th of the month, or a number of days added to your terms date, such as 14 days after the terms date.
    Payment Terms (Oracle Payables Help)

  • How i can calculate the backplane speed & throughput of cisco 48 1G 2960S switch?

    How i can calculate the backplane speed & throughput of cisco 48 1G 2960S switch?

    Disclaimer
    The  Author of this posting offers the information contained within this  posting without consideration and with the reader's understanding that  there's no implied or expressed suitability or fitness for any purpose.  Information provided is for informational purposes only and should not  be construed as rendering professional advice of any kind. Usage of this  posting's information is solely at reader's own risk.
    Liability Disclaimer
    In  no event shall Author be liable for any damages whatsoever (including,  without limitation, damages for loss of use, data or profit) arising out  of the use or inability to use the posting's information even if Author  has been advised of the possibility of such damage.
    Posting
    Calculate?  Calculate for wirespeed/line-rate?  If the latter, take all the port bandwidths, and assuming they are duplex, double for necessary fabric bandwidth.  I.e. 48 gig ports would need a 96 Gbps fabric.  Take all your port bandwidths, and allow 1.448 Mpps per gig (for minimum size Ethernet packets), i.e. 48 gig ports would need 69.5 Mpps.  Once you have required fabric bandwidth and PPS, you can compare to vendor's specs.

  • How can I calculate the request time ?

    Hello,
    How can I calculate the total consume time in each request ?
    For example, I want to start calculating the time when I click on a Link or a button and the end time when it completed load the page !
    Eric

    You could use a filter like this one:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.text.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    public class TimeFilter implements Filter {
        // The filter configuration object we are associated with.  If
        // this value is null, this filter instance is not currently
        // configured.
        private FilterConfig filterConfig = null;
        private static final boolean debug = false;
        private long start = 0;
        private long end = 0;
        public TimeFilter() {
        private void doBeforeProcessing(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {
            if (debug) log("CalendarFilter:DoBeforeProcessing");
            System.out.print("In Filter  ");
            this.start = System.currentTimeMillis();
            System.out.println((new java.util.Date()).toString() +
                               " start request ");
        private void doAfterProcessing(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {
            if (debug) log("TimeFilter:DoAfterProcessing");
            System.out.println("Completion Time = " + (System.currentTimeMillis() - start));
         * @param request The servlet request we are processing
         * @param result The servlet response we are creating
         * @param chain The filter chain we are processing
         * @exception IOException if an input/output error occurs
         * @exception ServletException if a servlet error occurs
        public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain)
        throws IOException, ServletException {
            if (debug) log("TimeFilter:doFilter()");
            doBeforeProcessing(request, response);
            Throwable problem = null;
            try {
                chain.doFilter(request, response);
            catch(Throwable t) {
                problem = t;
                t.printStackTrace();
            doAfterProcessing(request, response);
            // If there was a problem, we want to rethrow it if it is
            // a known type, otherwise log it.
            if (problem != null) {
                if (problem instanceof ServletException) throw (ServletException)problem;
                if (problem instanceof IOException) throw (IOException)problem;
                sendProcessingError(problem, response);
         * Return the filter configuration object for this filter.
        public FilterConfig getFilterConfig() {
            return (this.filterConfig);
         * Set the filter configuration object for this filter.
         * @param filterConfig The filter configuration object
        public void setFilterConfig(FilterConfig filterConfig) {
            this.filterConfig = filterConfig;
         * Destroy method for this filter
        public void destroy() {
         * Init method for this filter
        public void init(FilterConfig filterConfig) {
            this.filterConfig = filterConfig;
            if (filterConfig != null) {
                if (debug) {
                    log("TimeFilter:Initializing filter");
         * Return a String representation of this object.
        public String toString() {
            if (filterConfig == null) return ("TimeFilter()");
            StringBuffer sb = new StringBuffer("TimeFilter(");
            sb.append(filterConfig);
            sb.append(")");
            return (sb.toString());
        private void sendProcessingError(Throwable t, ServletResponse response) {
            String stackTrace = getStackTrace(t);
            if(stackTrace != null && !stackTrace.equals("")) {
                try {
                    response.setContentType("text/html");
                    PrintStream ps = new PrintStream(response.getOutputStream());
                    PrintWriter pw = new PrintWriter(ps);
                    pw.print("<html>\n<head>\n</head>\n<body>\n"); //NOI18N
                    // PENDING! Localize this for next official release
                    pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
                    pw.print(stackTrace);
                    pw.print("</pre></body>\n</html>"); //NOI18N
                    pw.close();
                    ps.close();
                    response.getOutputStream().close();;
                catch(Exception ex){ }
            else {
                try {
                    PrintStream ps = new PrintStream(response.getOutputStream());
                    t.printStackTrace(ps);
                    ps.close();
                    response.getOutputStream().close();;
                catch(Exception ex){ }
        public static String getStackTrace(Throwable t) {
            String stackTrace = null;
            try {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                t.printStackTrace(pw);
                pw.close();
                sw.close();
                stackTrace = sw.getBuffer().toString();
            catch(Exception ex) {}
            return stackTrace;
        public void log(String msg) {
            filterConfig.getServletContext().log(msg);
    }and in the web.xml :
       <filter>
            <filter-name>TimeFilter</filter-name>
            <filter-class>
                com.filter.TimeFilter
            </filter>
        <filter-mapping>
            <filter-name>TimeFilter</filter-name>
            <url-pattern>/services/*</url-pattern>
        </filter-mapping > 

  • How would I get the date of last Monday?

    How would I get the date of last Monday?

    I've done the following, does it seem right?
    public static const millisecondsPerDay:int = 1000 * 60 * 60 *
    24;
    * This function sets the mimimum and maximum range
    private function sliceChartWeek():void{
    var max:Date = new Date();//current date is our max from
    which we will calculate the min
    var day:uint = max.day;
    var min:Date = new Date(max.getTime() - (millisecondsPerDay
    * (max.day - 1)));
    dateTimeAxis.minimum = min;
    }

Maybe you are looking for