Grouping based on Start and End Year

Hello everyone,
Need your help in solving one SQL query
My data look like this
cid rid year title
52     1000     2001     1
52     1000     2002     1
52     1000     2003     6
52     1000     2004     6
52     1000     2005     6
52     1000     2007     1
52     1001     2003     1
52     1001     2004     1
52     1001     2005     1
52     1001     2006     3
52     1001     2007     3
output I am required to produce is
CID          RID          START-END     TITLE
52          1000     2001-2002     1
52          1000     2003-2005     6
52          1000     2007-2007     1
52          1001     2003-2005     1
52          1001     2006-2007     3
here is script for table and data
create table T (
cid NUMBER,
rid NUMBER,
start_year NUMBER,
title NUMBER
insert into t (cid, rid, start_year, title) values (52, 1000, 2001, 1);
insert into t (cid, rid, start_year, title) values (52, 1000, 2002, 1);
insert into t (cid, rid, start_year, title) values (52, 1001, 2003, 1);
insert into t (cid, rid, start_year, title) values (52, 1000, 2003, 6);
insert into t (cid, rid, start_year, title) values (52, 1001, 2004, 1);
insert into t (cid, rid, start_year, title) values (52, 1000, 2004, 6);
insert into t (cid, rid, start_year, title) values (52, 1001, 2005, 1);
insert into t (cid, rid, start_year, title) values (52, 1000, 2005, 6);
insert into t (cid, rid, start_year, title) values (52, 1001, 2006, 3);
insert into t (cid, rid, start_year, title) values (52, 1001, 2007, 3);
insert into t (cid, rid, start_year, title) values (52, 1000, 2007, 1);
commit;
I was able to go this far (some what close to what I need but not exactly what I need)
select cid, rid, min(year2), max(year1), title
from (
select tc.cid, tc.rid, tc.title, tc.start_year year1, tp.start_year year2, decode (tc.title, tp.title, 'N', 'Y') gap
from t tc,
t tp
where tc.start_year -1 = tp.start_year
and tc.cid = tp.cid
and tc.rid = tp.rid
group by cid, rid, title, gap
Thanks for considering
Naseer,
Houston-TX

I'm not sure how elegant this is, but the following tweak to your query solved the problem I posed above:
WITH      got_grp_id     AS
     SELECT     cid, rid, start_year, title
     ,     ROW_NUMBER () OVER ( PARTITION BY  cid, rid
                               ORDER BY          start_year
           -     ROW_NUMBER () OVER ( PARTITION BY  cid, rid, title
                             ORDER BY          start_year
              + NVL(LAG(start_year,1) OVER(PARTITION BY cid,rid,title
                                       ORDER BY cid,rid,title),start_year - 1
                                   ) + 1 - start_year        AS grp_id
     FROM    t
SELECT       cid
,       rid
,       MIN (start_year) || '-'
                        || MAX (start_year)     AS start_end
,       title
FROM       got_grp_id
GROUP BY  cid, rid, title, grp_id
ORDER BY  cid, rid, start_end
CID  RID  START_END  TITLE 
52  1000  2001-2002  1 
52  1000  2007-2007  1 
52  1001  2003-2005  1 
52  1001  2006-2007  3 

Similar Messages

  • Hyperion Planning dynamic forms based on start and end date across years

    Hi All,
    I have a requirement where i need to be able to view a form showing periods across years that are dynamically built depending on the start and end dates. If i have a start date of 01/11/2009 and an end date of 31/7/2013 i want to be able to view a form that shows all of the periods (Jan,Feb etc) in a form that is driven by these dates, in addition it will need to show the actual scenario up to the current month and the forecast from the current month to the end date. So basically if a user inputs the start and end dates the form will display the relevant periods driven by these dates.
    Any tips very much appreciated!

    Hello,
    This is difficult to realize, but you can get quite far with a workaround. The first question is, where do you want to input your selection of time periods? Assuming you have a webform with the complete timeline in months and years and you type in the start period and end period.
    Webforms have the option to suppress rows and columns.
    This can be extended with option of empty cells or not empty cells.
    You will need to apply your creativity on this.
    Put every month-year combination in a column and add the suppression.
    Calculate the timeline between start period and end period with a dummy member, so data exists for these and columns will show.
    Maybe you will need to copy the required timeline into a separate version for this, to avoid having periods which were outside the selection and still have data.
    I hope these hints help a bit in this challenge.
    Regards,
    Philip Hulsebosch
    www.trexco.nl

  • Prorating Wage Type in IT0014 based on start and end dates

    Hi experts
    I have a scenario wherein I want to prorate a Wage type according to the start and end dates in Infotype 0014. I have tried setting the Processing Class 10 to 1. When I do this, the system prorates according to the start date. Example:
    If the start and the end dates for wagetype 4000 are: 24.05.2014 to 31.12.9999, amount is 1000 and the payroll period is May'2014, then amount calculated is 258.06, which is correct.
    If however, the start and the end dates for wagetype 4000 are: 01.05.2014 to 24.05.2014, amount is 1000 and the payroll period is May'2014, the system generates the amount 1000, which is incorrect.
    How can we handle this? Please help.
    Regards
    Divya Tiwari

    Hi Divya,
    Please check the below mentioned pcr's in your system.
    UW14 and X011
    Check above mentioned pcrs in subschemas INBD,ZNAP and share me the existing pcr's screenshot in your system.
    Regards,
    Haranath

  • Substring based on start and end characters

    All
    I want to perform susbstring of a string based on start character and end character
    Please look at the below example:
    str = "john$peter$rahul;
    In this string i need to fetch charcters between $ i.e. defg
    I cant use startindex and endindex as string may vary.
    Can anybody help?

    praveen.kb wrote:
    Thanks for the reply...
    But i need string between 2 $ that is
    peter only.. The string may contain any number of $.
    This is the example:
    str = "Prepared BY: $NAME$                                                          ENTITY:$ENT$";I need only NAME and ENT. How can i do this?In your first example, you just wanted the middle word. Now you skip the String
    "$                                                          ENTITY:$"which is also between two $ signs.
    You need to explain yourself a bit more.

  • Summarise the results based on start and end dates

    Hi All,
    Can some body tells how to summarise a table results like in the below example?
    I need help to get results as poc_dates_result from poc_dates table.
    The data is supplied below to create the above tables.
    Please provide the queries to convert poc_dates to poc_dates_result?
    DROP TABLE poc_dates;
    create table poc_dates
    pid number
    ,start_dte date
    ,end_dte date
    ,prod char(3)
    insert into poc_dates values(1,'01-JAN-2000','01-FEB-2000','PD1');
    insert into poc_dates values(1,'02-FEB-2000','01-MAR-2000','PD1');
    insert into poc_dates values(1,'02-MAR-2000','01-APR-2000','PD1');
    insert into poc_dates values(1,'02-APR-2000','15-APR-2000','PD2');
    insert into poc_dates values(1,'16-APR-2000','24-APR-2000','PD2');
    insert into poc_dates values(1,'25-APR-2000','01-MAY-2000','PD3');
    insert into poc_dates values(1,'02-MAY-2000','16-MAY-2000','PD3');
    insert into poc_dates values(1,'17-MAY-2000','18-MAY-2000','PD1');
    insert into poc_dates values(1,'19-MAY-2000','25-MAY-2000','PD1');
    insert into poc_dates values(2,'01-JAN-2000','01-FEB-2000','PD1');
    insert into poc_dates values(2,'02-FEB-2000','01-MAR-2000','PD1');
    insert into poc_dates values(2,'02-MAR-2000','01-APR-2000','PD2');
    insert into poc_dates values(2,'02-APR-2000','15-APR-2000','PD1');
    insert into poc_dates values(2,'16-APR-2000','25-APR-2000','PD3');
    insert into poc_dates values(3,'01-JAN-2000','01-FEB-2000','PD1');
    insert into poc_dates values(3,'02-FEB-2000','01-MAR-2000','PD1');
    insert into poc_dates values(3,'02-MAR-2000','01-APR-2000','PD2');
    insert into poc_dates values(4,'01-JAN-2000','01-FEB-2000','PD1');
    insert into poc_dates values(4,'02-FEB-2000','01-MAR-2000','PD2');
    insert into poc_dates values(5,'01-JAN-2000','01-FEB-2000','PD1');
    commit;
    drop table poc_dates_result;
    create table poc_dates_result
    pid number
    ,start_dte date
    ,end_dte date
    ,prod char(3)
    insert into poc_dates_result values(1,'01-JAN-2000','01-APR-2000','PD1');
    insert into poc_dates_result values(1,'02-APR-2000','24-APR-2000','PD2');
    insert into poc_dates_result values(1,'25-APR-2000','16-MAY-2000','PD3');
    insert into poc_dates_result values(1,'17-MAY-2000','25-MAY-2000','PD1');
    insert into poc_dates_result values(2,'01-JAN-2000','01-MAR-2000','PD1');
    insert into poc_dates_result values(2,'02-MAR-2000','01-APR-2000','PD2');
    insert into poc_dates_result values(2,'02-APR-2000','15-APR-2000','PD1');
    insert into poc_dates_result values(2,'16-APR-2000','25-APR-2000','PD3');
    insert into poc_dates_result values(3,'01-JAN-2000','01-MAR-2000','PD1');
    insert into poc_dates_result values(3,'02-MAR-2000','01-APR-2000','PD2');
    insert into poc_dates_result values(4,'01-JAN-2000','01-FEB-2000','PD1');
    insert into poc_dates_result values(4,'02-FEB-2000','01-MAR-2000','PD2');
    insert into poc_dates_result values(5,'01-JAN-2000','01-FEB-2000','PD1');
    commit;
    select * from poc_dates;
    PID     START_DTE END_DTE     PROD
    1     1/01/2000     1/02/2000     PD1
    1     2/02/2000     1/03/2000     PD1
    1     2/03/2000     1/04/2000     PD1
    1     2/04/2000     15/04/2000     PD2
    1     16/04/2000 24/04/2000     PD2
    1     25/04/2000 1/05/2000     PD3
    1     2/05/2000     16/05/2000     PD3
    1     17/05/2000 18/05/2000     PD1
    1     19/05/2000 25/05/2000     PD1
    2     1/01/2000     1/02/2000     PD1
    2     2/02/2000     1/03/2000     PD1
    2     2/03/2000     1/04/2000     PD2
    2     2/04/2000     15/04/2000     PD1
    2     16/04/2000 25/04/2000     PD3
    3     1/01/2000     1/02/2000     PD1
    3     2/02/2000     1/03/2000     PD1
    3     2/03/2000     1/04/2000     PD2
    4     1/01/2000     1/02/2000     PD1
    4     2/02/2000     1/03/2000     PD2
    5     1/01/2000 1/02/2000     PD1
    select * from poc_dates_result;
    PID     START_DTE END_DTE PROD
    1     1/01/2000     1/04/2000     PD1
    1     2/04/2000     24/04/2000     PD2
    1     25/04/2000 16/05/2000     PD3
    1     17/05/2000 25/05/2000     PD1
    2     1/01/2000     1/03/2000     PD1
    2     2/03/2000     1/04/2000     PD2
    2     2/04/2000     15/04/2000     PD1
    2     16/04/2000 25/04/2000     PD3
    3     1/01/2000     1/03/2000     PD1
    3     2/03/2000     1/04/2000     PD2
    4     1/01/2000     1/02/2000     PD1
    4     2/02/2000     1/03/2000     PD2
    5     1/01/2000     1/02/2000     PD1
    Thanks,
    CD
    Edited by: cdprasad on Jul 15, 2010 10:52 AM

    I'm sure there is simplest way to achieve this, but here below a try :
    SQL> select pid,min(start_dte),max(end_dte),prod
      2  from   (select pid,start_dte,end_dte,prod,sum(flg) over (order by pid,prod,start_dte) sm
      3          from   (select pid,start_dte,end_dte,prod,
      4                         decode(start_dte-1,lag(end_dte) over (partition by pid,prod order by start_dte),0,1) flg
      5                  from   poc_dates))
      6  group by pid,prod,sm
      7* order by 1,4,2
    SQL> /
           PID MIN(START_DTE)  MAX(END_DTE)    PRO
             1 01-JAN-00       01-APR-00       PD1
             1 17-MAY-00       25-MAY-00       PD1
             1 02-APR-00       24-APR-00       PD2
             1 25-APR-00       16-MAY-00       PD3
             2 01-JAN-00       01-MAR-00       PD1
             2 02-APR-00       15-APR-00       PD1
             2 02-MAR-00       01-APR-00       PD2
             2 16-APR-00       25-APR-00       PD3
             3 01-JAN-00       01-MAR-00       PD1
             3 02-MAR-00       01-APR-00       PD2
             4 01-JAN-00       01-FEB-00       PD1
             4 02-FEB-00       01-MAR-00       PD2
             5 01-JAN-00       01-FEB-00       PD1
    13 rows selected.Nicolas.

  • SSRS Bar Chart grouping date series into Months, setting scaler start and end ranges

    I've been trying to solve this issue for a few days now without writing a sql script to create a "blank" for all of missing data points so that I get a bar for each month.  I have date series (by day) data points grouped by two items
    that creates a set of bar charts.  EG:  one chart per product in the tablix detail grouped to site level.
    My issue is I would like the start and end of the charts to be the same for all charts and the only way I get it to work is with a chart that continues to show each date on the chart. 
    EG:
    I have the graph start and end points set and scaling by month as I would like but each bar is a day instead of aggregating to a month level.   My issue I hope to find a workaround for is if I go to Category Groups and define the grouping
    to group with a year and month function the series is no longer treated as date data and I cannot control scaling.  It works fine if all months have activity, but I can't figure out how to always have all charts start at "May 2012" in this example. 
    The only start and end point that I've been able to get to work once doing this are integer based, eg normal start would be 1 for each graph, but 1 doesn't equate to the same month from chart to chart.
    I hope SSRS can provide the solution.  I do know I can write a query that creates a ZERO value for each month/product/site but I don't want to leave the client with a query like that to support.
    -cybertosis

    Hi cybertosis,
    If I understand correctly, you want to display all month category label in the X-Axis. You have configure the Scalar Axis, however, it cannot display the requirement format.
    In your case, if we want the specific data format, we can configure Number property to set the corresponding Category data format. Please refer to the following steps:
    Right click the X-Axis, select Horizontal Axis Properties.
    Click Number in the left pane. Click Date option in the Category dialog box.
    Then, select Jan 2000 option.
    Please refer to the following screenshot below:
    If there are any misunderstanding, please feel free to let me know.
    Regards,
    Alisa Tang
    If you have any feedback on our support, please click
    here.
    Alisa Tang
    TechNet Community Support

  • Effective start and end dates for roles/group assignment

    Hi,
    Does Access Manager (in legacy or realm) mode support effective start date/end date on a role/group assignment on a user?
    Thanks,
    Srinivas

    Hi Ankush,
    I am also of the same opinion. Start and end dates can probably be enforced by a policy condition in AM but would lead to proliferation of policies as we would end up creating policies per role entitlement duration for a user.
    Any thoughts on whether the sunrise/sunset concept of Identity Manager can be used for this requirement.
    Thanks,
    Srinivas

  • Text Variables to show Start and End Date of Fiscal Year Period

    Hi,
    I am creating a query that has user enter a starting fiscal year period and posts information by Fiscal Year Period going back 14 periods.  I am able to put the fiscal year period in the heading for all periods, but would also like to add the start and end calendar day for each listed period.  Can that be done using a replacement path text variable or is that something more for a customer exit variable?
    Thanks in advance for any thoughts provided.
    Bill

    Hi,
    This is one of my exit that display the calmonth (offset -12). Usefull when I have to retrieve in a KF a complete rolling year depending one calmonth.
    S_VMUCMN is my selection variable
    S_TXTCMN_M12 is my text variable calmonth-12
    S_TXTCMN_M0 is my text variable for selected calmonth.
    WHEN 'S_TXTCMN_M12'.
        IF i_step = '2'.
          LOOP AT i_t_var_range INTO loc_var_range WHERE vnam = 'S_VMUCMN'.
            CLEAR l_s_range.
            " First day of the selected month
            CONCATENATE loc_var_range-low '01' INTO l_calday.
            CALL FUNCTION 'YFRBW_FUM_CAL_DATE_IN_INTERVAL'
              EXPORTING
                date      = l_calday
                months    = 12
                signum    = '-'
              IMPORTING
                calc_date = l_calday.
            l_s_range-low = l_calday+0(6).
            l_s_range-sign = 'I'.
            l_s_range-opt = 'EQ'.
            APPEND l_s_range TO e_t_range.
            EXIT.
          ENDLOOP.
        ENDIF.
    Thus, in KF header you have to put the two text variable to display the complete period.
    Hope it helps,

  • Function module to derive start and end dates from fiscal year and period.

    Hi,
    I want to know a function module to derive start and end dates from fiscal year and period.
    ie: If I have say fiscal year '2010' and period '07', then the start date of this period would be '01.10.2010'.
    Thanks.
    Moderator Messge: Basic Date questions are not allowed.
    Edited by: kishan P on Oct 18, 2010 4:45 PM

    Hi,
    This is one of my exit that display the calmonth (offset -12). Usefull when I have to retrieve in a KF a complete rolling year depending one calmonth.
    S_VMUCMN is my selection variable
    S_TXTCMN_M12 is my text variable calmonth-12
    S_TXTCMN_M0 is my text variable for selected calmonth.
    WHEN 'S_TXTCMN_M12'.
        IF i_step = '2'.
          LOOP AT i_t_var_range INTO loc_var_range WHERE vnam = 'S_VMUCMN'.
            CLEAR l_s_range.
            " First day of the selected month
            CONCATENATE loc_var_range-low '01' INTO l_calday.
            CALL FUNCTION 'YFRBW_FUM_CAL_DATE_IN_INTERVAL'
              EXPORTING
                date      = l_calday
                months    = 12
                signum    = '-'
              IMPORTING
                calc_date = l_calday.
            l_s_range-low = l_calday+0(6).
            l_s_range-sign = 'I'.
            l_s_range-opt = 'EQ'.
            APPEND l_s_range TO e_t_range.
            EXIT.
          ENDLOOP.
        ENDIF.
    Thus, in KF header you have to put the two text variable to display the complete period.
    Hope it helps,

  • Contract Start and End Dates in Sales Order

    Hi
    I have a situation where a service item is bundled with a deliverable item. The order is as follows
    Line Item    Mat                                                                 Qty            Higher Level Item               
    10              Item No.1 (Physical Item)                                  1             
    20              Item No.2 (Service Item)                                    1               10
    For the deliverable item 10 , Revenue is recognized immediately. For the Service item no.20 , revenue needs to be recognized over a period of 1 Year (It is a 1 year service contract).
    The whole order is created via BAPI from an external 3rd party order capture system.
    In order to do revenue recognition properly for service items , SAP I believe has 2 options
    1. Based on Billing plan dates
    2. Based on contract start dates
    Since order with both the line items need to produce 1 invoice, I cannot use billing plan . The only other option is to use contract start and end dates. I have enabled contract data at the sales order level. So when I enter the contract start and end dates manually at the line item level and set the item category to recognize revenue based on contract start and end dates based on time-based revenue recognition it is working fine.
    But I need a way to automate the population of contract start and end dates at the line item level. My ABAP guy is not able to find a user exit that can change the XVEDA or any VEDA structure in any of the user exits.
    I guess the SAP SD gurus out there would have definitely dealt with a situation of product bundling (Service and non-service items in the same sales order with one billing document , but seperate revenue recognition for service and non-service items)
    Please help.
    Thnx
    Siva

    Hi Siva,
    Kindly let me know what criteria you want to give for automatic population of start date of contract...
    Standard SAP comes with a few baseline dates for contract start date and we can control this from customization itself. 
    01     Today's date
    02     Contract start date
    04     Acceptance date
    05     Installation date
    06     Date contract signed
    07     Billing date/Invoice date
    08     CntrctStDate+contract duration
    09     Contract end date
    If you have some criteria which is not covered here, then let me know and i will try to provide some help then.
    Thanks
    Kapil Sharma

  • Reduce Working Days by Emp Start and End Dates

    I'm banging my head trying to get this working. The set-up:
    DimResources table with various employee information including a Start and End Date.
    A Calendar table with FullDate, Year, Quarter....WorkingDays (1 for working and 0 for non-working) and WorkingDayNumber (working days increased by 1, weekends are not).
    Page View report with page view filters for Business, Role, Month, Week, Year.
    In the calculation the denominator is total working days for the period * 8. Works great. Further reduced by any submitted time off. Again, so far so good. The part I'm having trouble with is trying to further reduce total working days by
    the number of days the person wasn't available in a month, defined by the person's start or end date.
    The calculated field works great when only 1 person is selected. As soon as more than 1 person is selected or the slicer is cleared, an error is thrown.
    Any ideas on what is wrong or better ways to accomplish what's needed?
    TotalWorkingDays2CF=CALCULATE
     SUM(Calendar[WorkingDays]),
                    FILTER(Calendar,Calendar[WorkingDays]=1),
                    Calendar, DATESBETWEEN(Calendar[FullDate],SUM(DimResources[Start Date]),SUM(DimResources[End Date]))
    Error:
    <detail>
      <ErrorCode>rsErrorExecutingCommand</ErrorCode>
      <Message>Query couldn't run for dataset 'Tablix41DataSet'.</Message>
      <ProductName>Power View</ProductName>
      <ProductVersion>11.0.2150.3</ProductVersion>
      <MoreInfo>MdxScript(Model) (10, 27) Calculation error in measure 'Calendar'[TotalWorkingDays2CF]: An invalid numeric representation of a date value was encountered.</MoreInfo>
    </detail>
    Dennis DeRobertis

    ok, but this is not a running total but just a sub-total/grand-total
    so what you can do is the following:
    create two measures - first calculate the workdays per ressourcen and second use SUMX() to get the sub-/grand-total if multiple employees are selected (e.g. subgroups, groups,division, etc)
    WorkdaysRessource:=CALCULATE(
    COUNTROWS('Date'),
    FILTER('Date',
    'Date'[Date] >= CALCULATE(MIN('DimResources'[Start Date]))
    && 'Date'[Date] <= CALCULATE(MIN('DimResources'[End Date])))
    Workdays:=CALCULATE:=SUMX(
    'DimResources',
    [WorkdaysRessource]
    hth,
    gerhard
    Gerhard Brueckl
    blogging @ http://blog.gbrueckl.at
    working @ http://www.pmOne.com

  • Getting the start  and end dates of the week

    Hi,
    I was stuck with a problem in getting the start date and end date of the week,i know the month ,week and year also,with these three values how can i get the start and end dates of a week.please help me
    Thanks

    There is no simple way. It has to be a math calculation.
    There are several ways you can get the dates. First you have to know what day is January 1st and what day is december 31st for a particular year. Second you have to check whether the given year is a leap year or not. Based on the abvove information you should be able to find out what day is a particular date.
    Hope this helps to get you started.
    - Venkat Dhurjati.

  • Effective start and end dates for a compensation workbench plan

    Hi all,
    We are having a requirement where we want to get the data respective to current plan for reporting purposes. What i have noticed is there is no such thing as effective_start_date and effective_end_date directly in all the cwb tables.
    The different dates we are looking at to capture the data are
    enrt_perd_start_dt and enrt_perd_end_dt
    upd_strt_dt and upd_end_dt
    within_yr_strt_dt and within_yr_end_dt
    But we have same plan with different enrollment period and start dates. We are planning to use max(data_freeze_date or lf_evt_occrd_dt) to get
    the records.
    select max(nvl(bcpdx.data_freeze_date, bcpdx.lf_evt_ocrd_dt))
    from ben_cwb_pl_dsgn bcpdx
    where bcpdx.pl_id = p_pl_id)
    Catch with this is, We have 62 business groups off which only 50 might run the plan next year and ohters might not. in that case it will also return data for all the BG's including the 12 BG's where plan has not been run for that year.
    Any suggestions or help will greatly be appreciated.
    Thanks
    Hari

    Hi Ankush,
    I am also of the same opinion. Start and end dates can probably be enforced by a policy condition in AM but would lead to proliferation of policies as we would end up creating policies per role entitlement duration for a user.
    Any thoughts on whether the sunrise/sunset concept of Identity Manager can be used for this requirement.
    Thanks,
    Srinivas

  • Adding a summary column in a table which contains the start and end dates in the week

    Hi,
    I've got a DIMENSION DATE table and want to add in another column which shows the start and end date of the week.
    See below, the new column is WEEKOFYEARTEXT.
    Does anybody know how i may generate this column using SQL and using the existing columns?
    Umar Javed

    See:  http://www.sqlusa.com/bestpractices/datetimeconversion/
    DECLARE @Year INT = '2015';
    WITH cteDays AS (SELECT DayOfYear=Dateadd(dd, number,
    CONVERT(DATE, CONVERT(char(4),@Year)+'0101'))
    FROM master.dbo.spt_values WHERE type='P'),
    CTE AS (SELECT DayOfYear, WeekOfYear=DATEPART(week,DayOfYear)
    FROM cteDays WHERE YEAR(DayOfYear)= @YEAR)
    SELECT WeekOfYear, StartOfWeek=MIN(DayOfYear), EndOfWeek=MAX(DayOfYear)
    FROM CTE GROUP BY WeekOfYear ORDER BY WeekOfYear;
    WeekOfYear StartOfWeek EndOfWeek
    1 2015-01-01 2015-01-03
    2 2015-01-04 2015-01-10
    3 2015-01-11 2015-01-17
    4 2015-01-18 2015-01-24
    5 2015-01-25 2015-01-31
    6 2015-02-01 2015-02-07
    7 2015-02-08 2015-02-14
    8 2015-02-15 2015-02-21
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • How to get fiscal period based on date and Fiscal year?

    Hi Guys,
               Can anybody tell me how to get Fiscal period based on date and Fiscal Year or fiscal year variant?
    Thanks,
    Gopi.

    Hi,
    Please refer the code below:
    *: Report:  ZFISCALYR                                                  :
    *: Date  :  2004                                                       :
    *: Description: Demonstrates how to return the corresponding fiscal    :
    *:              year and posting period for a company code and posting :
    *:              date or posting date and fiscal year variant.          :
    REPORT  zfiscalyr NO STANDARD PAGE HEADING.
    TABLES: ekko.
    PARAMETERS:     p_bukrs TYPE ekko-bukrs,
                    p_bedat TYPE ekko-bedat.
    DATA: gd_fiscalyr  TYPE bapi0002_4-fiscal_year,
          gd_fiscalp   TYPE bapi0002_4-fiscal_period.
    DATA: gd_fiscalyr2 TYPE T009B-BDATJ,
          gd_fiscalp2  TYPE bapi0002_4-fiscal_period.
    DATA: gd_periv     TYPE t009-periv.
    *START-OF-SELECTION.
    START-OF-SELECTION.
    * get fiscal year and period - (requires date and company code)
      CALL FUNCTION 'BAPI_COMPANYCODE_GET_PERIOD'
        EXPORTING
          companycodeid = p_bukrs
          posting_date  = p_bedat
        IMPORTING
          fiscal_year   = gd_fiscalyr
          fiscal_period = gd_fiscalp.
    * Alternative fiscal year function module
    * - (requires date and fiscal year variant code from T009 table)
    * gets first entry in fiscal year variant table (will need to choose
    * correct one from table rather than just using first entry)
      SELECT SINGLE periv
        FROM t009
        INTO gd_periv.
    * get fiscal year and period
      CALL FUNCTION 'DETERMINE_PERIOD'
        EXPORTING
          date                      = p_bedat
    *    PERIOD_IN                 = '000'
          version                   = gd_periv
       IMPORTING
          period                    = gd_fiscalp2
          year                      = gd_fiscalyr2
       EXCEPTIONS
          period_in_not_valid       = 1
          period_not_assigned       = 2
          version_undefined         = 3
          OTHERS                    = 4.
    *END-OF-SELECTION.
    END-OF-SELECTION.
      WRITE:/ 'From function module: BAPI_COMPANYCODE_GET_PERIOD',
            / 'Fiscal year is:', gd_fiscalyr,
            / 'Fiscal period is:', gd_fiscalp.
      SKIP.
      WRITE:/ 'From function module: DETERMINE_PERIOD',
            / 'Fiscal year is:', gd_fiscalyr2,
            / 'Fiscal period is:', gd_fiscalp2.
    Thanks,
    Sriram Ponna.
    Edited by: Sriram Ponna on Apr 17, 2008 8:59 PM

Maybe you are looking for