Need to fetch value from a table based on data range

Hello there,
I was hoping that the community could give me a hand with this little puzzle I got.
I am currently creating a Time Dimension for a data wharehouse, and I have the requirement to populate a column named SEASON (e.g: Summer, Winter, Spring, Autumn) for each date row. So for the 20/Dec/2013, the Season column must say Winter.
Here is now my Time Dimension table looks like, without the Season information (which I yet have to load):
DimTime Table
TIMEID
FULLDATE
YEAR
SEASON
MONTH
MONTHDAY
WEEK
WEEKDAY
274
02-MAR-10
2010
3
2
9
2
275
03-MAR-10
2010
3
3
9
3
276
04-MAR-10
2010
3
4
9
4
277
05-MAR-10
2010
3
5
9
5
278
06-MAR-10
2010
3
6
9
6
279
07-MAR-10
2010
3
7
9
7
This entire table is being populated using Oracle functions to manipulate a date field from another table, named PDATE:
My ETL Code
INSERT INTO DimTime(timeid, fulldate, year, month, monthday, week, weekday)
SELECT tim_seq.NEXTVAL, pdate, year, month, monthday, week, weekday
FROM (SELECT DISTINCT pdate, EXTRACT(year from pdate) year, EXTRACT(month from pdate) month,
EXTRACT(day FROM pdate) monthday, to_number(to_char(to_date(pdate,'DD/MM/YY'),'IW')) week,
TO_CHAR(pdate, 'D') weekday
FROM Performance PER
ORDER BY pdate);
NOTE: Code considers the table DimTime to be truncated every time it loads (i.e.: I don't need to consider additional loads).
As you can see, Season wasn't populated. Since the solstices and equinoxes vary for each year, I can't just say that Summer start at a given date (e.g: 21 of June) because one year it could be the 19/Jun, another the 22/Jun, etc. So in order to solve this problem, I have a table named Season which defines the START and END dates for the seasons:
Season Table
SEASON#
SEASONNAME
YEAR
DATEFROM
DATETO
1
Spring
2010
01-MAR-10
30-MAY-10
2
Summer
2010
31-MAY-10
29-AUG-10
3
Autumn
2010
30-AUG-10
28-NOV-10
4
Winter
2010
29-NOV-10
27-FEB-11
5
Spring
2011
28-FEB-11
29-MAY-11
6
Summer
2011
30-MAY-11
28-AUG-11
7
Autumn
2011
29-AUG-11
27-NOV-11
8
Winter
2011
28-NOV-11
26-FEB-12
9
Winter
2009
30-NOV-09
28-FEB-10
This is the bit I don't know how to do. How can I make sure that I populate the correct Season in my DimTime table based on the season specified in the Season table?
Thanks in advance for your help!
Regards,
P.

Just join to table Season:
INSERT
  INTO DimTime(
               timeid,
               fulldate,
               year,
               month,
               monthday,
               week,
               weekday,
               seasonname
  SELECT  tim_seq.NEXTVAL,
          pdate,
          year,
          month,
          monthday,
          week,
          weekday
    FROM  (
           SELECT  DISTINCT pdate,
                            EXTRACT(year from pdate) year,
                            EXTRACT(month from pdate) month,
                            EXTRACT(day FROM pdate) monthday,
                            to_number(to_char(to_date(pdate,'DD/MM/YY'),'IW')) week,
                            TO_CHAR(pdate,'D') weekday,
                            seasonname
             FROM  Performance PER,
                   season
             WHERE pdate between datefrom and dateto
SY.

Similar Messages

  • To select from database table based on date range

    hi
    i have a selection screen in which date range is being given
    say eg 23/06/07  to 23/12/08
    based on this date i want to select data from a ztable
    eg i want to select a field amount from table
    and three is a field date range on the table
    for this particular field i want to select all records for amount field  and factual field falling wiithing this date range and sum it
    eg
    based on date range as in selcetion screen
    select amount( field1)  factual ( field2) from ztable into it_ztable where date = ?....
    please give me code for it  and how to sum all values as i will get from the ztable into internal table the two values as fetched from the ztable
    please suggest asap
    regards
    arora

    hi
    i am using
    sELECT field1 field2 FROM Ztable  INto it_matu
                       where DATE GE sl_dat-low    
                        AND  DATE LE sl_dat-high.   
    i am getting data in internal table but
    say i have twelve records now i want to sum it the both the columns into and use that sum final amount to display
    let me know how to use sume in the intrranal tabl do i need to use control statement
    how to use the sum for two columns and take into a serperate variable to display
    regards
    aRora

  • Help needed to merge values from two tables -

    We have these three test tables shown, which have a common ID; And amount fields; I want the -------
    test1.val = test2.val + test3.val
    when they have common ids in them;
    I have shown the test data below: And the expected output;
    NOTE: In database with real table values - each of them have millions of rows in them. So effeciency is very important here;
    SQL> desc test1;
    Name Null? Type
    ID NUMBER
    VAL NUMBER
    SQL> desc test2;
    Name Null? Type
    ID NUMBER
    VAL NUMBER
    SQL> desc test3;
    Name Null? Type
    ID NUMBER
    VAL NUMBER
    SQL> select * from test1;
    ID VAL
    1 50
    2 50
    3 55
    4 60
    5 20
    5 rows selected.
    SQL> select * from test2;
    ID VAL
    1 25
    1 25
    2 5
    2 5
    4 75
    5 rows selected.
    SQL> select * from test3;
    ID VAL
    1 25
    1 25
    2 5
    2 25
    2 25
    5 10
    6 rows selected.
    I EXPECT the output to be:
    SQL> select * from test1;
    ID VAL
    1 100
    2 65
    3 20
    4 75
    3 20
    5 10
    6 rows selected.

    Need help with the update queries - joining three tables -

  • Finding value in one table based on date = maximum date in another

    I have an event table that shows event dates and attendees but a customer now wants to see the titles of attendees at the time of the event.  I have an audit table that shows changes in title and the dates on which the change occurred however I am not sure how to do a SQL statement that would find the title whose date is less than the date of the event but greater than earlier title changes.
    Example:  in audit table I have:
    name1, title1, 1/23/2011  
    name1, title2, 2/1/2012  
    name1, title3, 3/1/2013
    name2, title1, 5/3/2012
    name2, title2, 8/1/2013
    In event table I have
    event1, name1, 3/2/2012 
    event2, name1, 1/30/2011 
    event3, name1, 6/3/2013 
    event4, name1, 5/3/2012
    event4, name2,  6/1/2012
    event5, name2, 9/1/2013
    Result I want is:
    event1, name1, title2  (event date > 2/1/2012 (title2 date) but < 3/1/2013 (title3 date)  
    event2, name1, title1   (event date > 1/23/2011 but < other title dates) 
    event3, name1, title3   (event date > highest title date) 
    event4, name1, title2    same as first example above 
    event4, name2, title1
    event5, name2, title2
    Is it possible to get result with SQL alone?
    Pat

    Analytic funstion solution:
    with audit_tbl as (
                       select 'name1' name,'title1' title,to_date('1/23/2011','mm/dd/yyyy') dt from dual union all
                       select 'name1','title2',to_date('2/1/2012','mm/dd/yyyy') from dual union all
                       select 'name1','title3',to_date('3/1/2013','mm/dd/yyyy') from dual union all
                       select 'name2','title1',to_date('5/3/2012','mm/dd/yyyy') from dual union all
                       select 'name2','title2',to_date('8/1/2013','mm/dd/yyyy') from dual
         event_tbl as (
                       select 'event1' event,'name1' name,to_date('3/2/2012','mm/dd/yyyy') dt from dual union all
                       select 'event2','name1',to_date('1/30/2011','mm/dd/yyyy') from dual union all
                       select 'event3','name1',to_date('6/3/2013','mm/dd/yyyy') from dual union all
                       select 'event4','name1',to_date('5/3/2012','mm/dd/yyyy') from dual union all
                       select 'event4','name2',to_date('6/1/2012','mm/dd/yyyy') from dual union all
                       select 'event5','name2',to_date('9/1/2013','mm/dd/yyyy') from dual
    select  e.event,
            e.name,
            a.title
      from  event_tbl e,
             select  name,
                     title,
                     dt from_dt,
                     lead(dt - 1,1,date '9999-12-31') over(partition by name order by dt) to_dt
               from  audit_tbl
            ) a
      where a.name = e.name
        and e.dt between a.from_dt and a.to_dt
      order by e.event,
               e.name,
               e.dt
    EVENT  NAME  TITLE
    event1 name1 title2
    event2 name1 title1
    event3 name1 title3
    event4 name1 title2
    event4 name2 title1
    event5 name2 title2
    6 rows selected.
    SQL>
    SY.

  • How to get value from a metric based on date, without effecting other colum

    Hi
    I have 2 metrics say Revenue and Total Revenue and Date Dim
    For a selected date in the prompt, Revenue should be shown for that date, where as Total Revenue should be shown for the past 15 days, based on the date in the prompt.
    How can I achieve this?
    Cheers
    Edited by: OBIAS on Feb 28, 2013 4:57 PM

    Set a presentation variable in the Date Dim prompt, P_DATE.
    Within the request, edit the formula for Revenue to be...
    FILTER("Revenue" USING ("Date" = @{P_DATE}))
    And set the formula for Total Revenue to be something like...
    FILTER("Total Revenue" USING ("Date" between TimestampAdd(SQL_TSI_DAY, -15, @{P_DATE}) and @{P_DATE}))
    JB

  • Values from CRCO Table.

    Hi all ,
    I need to retreive some values from CRCO table based on the balues fetched from AFRU table. I am writing a select like this
    select single KOKRS KOSTL into table itab from CRCO
              where OBJTY = 'A'
                 and OBJID  = AFRU-ARBID
                 and ENDDA >= AFRU-BUDAT
                 and BEGDA <= AFRU-BUDAT.
    As I need to retreive a single record from above select, but as a result i am getting multiple records.
    Can anybody tell me what other keys from AFRU I can specify in the select in order to fetch only a single record.
    Thanks,
    Mungala.

    Object ID you can get from ARBID from AFRU Table. Put value of ARBID in OBJID in table CRCO & get values of KOKRS & KOSTL. That value will be unique for an work center But if ARBID values are many for an AUFNR(order no.) that mean you are using different work center where in may be you are using different cost center(i think controlling area will remain same). & hence SAP creates different records.
    Regards
    Prashant Jaiswal

  • Query to split one row to multiple based on date range

    Hi,
    I need to split single row into multple based on date range defined in a column, start_dt and end_dt
    I have a data
    ID      From date             End_dt                measure
    1        2013-12-01         2013-12-03            1
    1        2013-12-04         2013-12-06            2
    2        2013-12-01         2013-12-02            11
    3        2013-12-03         2013-12-04          22
    I required output as
    ID      Date                      measure
    1        2013-12-01              1
    1        2013-12-02              1
    1        2013-12-03              1
    1        2013-12-04              2
    1        2013-12-05              2
    1        2013-12-06              2
    2        2013-12-01             11
    2        2013-12-02             11
    3        2013-12-03             22
    3        2013-12-04            22
    Please provide me sq, query for the same
    Amit
    Please mark as answer if helpful
    http://fascinatingsql.wordpress.com/

    Have a calendar table for example and then probably using UNION ALL from date  and stat date JOIN the Calendar table
    SELECT ID,From date  FROM tbl
    union all
    SELECT ID,End_dt FROM tbl
    with tmp(plant_date) as
       select cast('20130101' as datetime)
       union all
       select plant_date + 1
         from tmp
        where plant_date < '20131231'
    select*
      from  tmp
    option (maxrecursion 0)
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Fetch the values from internal table inside an internal table (urgent!!)

    data : BEGIN OF PITB2_ZLINFO occurs 0,
             BEGDA LIKE SY-DATUM,
             ENDDA LIKE SY-DATUM,
             PABRJ(4) TYPE N,                       "Payroll Year
             PABRP(2) TYPE N,                       "Pay. Period
             ZL LIKE PC2BF OCCURS 0,
           END OF PITB2_ZLINFO.
    I have a internal table like this,
    How to Fetch the values from internal table inside an internal table.
    Kindly Help me on this..
    Regards,
    Ram.

    Hi,
    Try this....
    Loop at PITB2_ZLINF0.
    Loop at PITB2_ZLINF0-ZL.
    endloop.
    Endloop.
    Thanks...
    Preetham S

  • Need of SQL query in selecting distinct values from two tables

    hi,
    I need a query for selecting distinct values from two tables with one condition.
    for eg:
    there are two tables a & b.
    in table a there are values like age,sex,name,empno and in table b valuses are such as age,salary,DOJ,empno.
    here what i need is with the help of empno as unique field,i need to select distinct values from two tables (ie) except age.
    can anybody please help me.
    Thanks in advance,
    Ratheesh

    Not sure what you mean either, but perhaps this will start a dialog:
    SELECT DISTINCT a.empno,
                    a.name,
                    a.sex,
                    b.salary,
                    b.doj
    FROM    a,
            b
    WHERE   a.empno = b.empno;Greg

  • Fetch value from Table with respect to APP_USER.

    Hi,
    i want to fetch value from Table with respect to APP_USER.
    i am using
    SELECT ID,NAME,FILE_OBJ_ID,MIME_TYPE,DOC_SIZE,BLOB_CONTENT,DESCRIPTION,UPLOAD_DATE,'Download' FROM DUMY_FILE where CREATED_BY =:APP_USER;
    Show me error
    failed to parse SQL query:
    ORA-00911: invalid characterThanks
    Edited by: 805629 on Jan 13, 2011 2:09 AM

    Hello,
    I too have the same problem.
    I am using this query:
    select manager from leave_mgmt where support_engg=:APP_USER
    and source type is SQL Query(return single value)
    but nothing is coming up in the text field. Its empty.
    Please advice. Thanks in advance.

  • How to retrieve 2 values from a table in a LOV

    Hi
    I'm pretty new to APEX. I try to retrieve two values from a table using a LOV. I have a table named DEBIT with then columns SITE, NAME and KEY
    I want to display NAME to the user in a list. When the user select an item from the list, I want to retrieve the data of the SITE and KEY column of this item in order to launch an SQL command based on this two values.
    How to retrieve thes two values whant the user chooses an item from the list ?
    I apologize for my english, being french.
    Regards.
    Christian

    Christian,
    From what I understood about your requirement, you want a 'select list with submit' which displays "NAME" and based on the value selected, you want to get the corresponding values for "SITE" and "KEY" from the table.
    <b>Step 1: Create a select list with submit, say P1_MYSELECT </b><br><br>
    Use something like this in the dynamic list of values for the select list: <br>
    SELECT NAME display_value, NAME return_value
    FROM DEBIT<br><br>
    <b>Step 2: Create a page process of type PL/SQL block. Also create 2 hidden items P1_KEY and P1_SITE. </b><br><br>
    In the PL/sQL, write something like:
    DECLARE
      v_key DEBIT.KEY%TYPE;
      v_site DEBIT.SITE%TYPE;
      CURSOR v_cur_myvals IS
              SELECT KEY, SITE
              FROM DEBIT
              WHERE NAME = :P1_MYSELECT;
    BEGIN
      OPEN v_cur_myvals;
      LOOP
              FETCH v_cur_myvals
              INTO  v_key,v_site;
              EXIT WHEN v_cur_myvals%NOTFOUND;
    :P1_KEY := v_key;   
    :P1_SITE := v_site; 
      END LOOP;
      CLOSE v_cur_myvals;
    END; <br><br>
    Then you can use these values for whatever purpose you need to.
    Hope this helps.

  • How to display the values from the table in the screen

    Hi,
    I have created a screen where i will enter the values for the field treshold amount and desc and if i press update button  .it will update the new values by overriting the existing values .
    Now i have got requirement i need to create a button show which will display the existing value from the table. always there will be only one entry...in this table
    Please can one give me idea...to do this
    or sample code...thanks in advance
    regards
    paveeeeee

    Define a function code 'SHOW' for your button. In your PAI module, when you check for various sy-ucomms, check for 'SHOW' also.
    Your code will be like this:
    Case sy-ucomm.
      when 'SHOW'.
         perform show_details.
    endcase.
    In the perform, you can fetch the data from the table and put it in global variables. In the PBO, move the data from the global variables to the screen fields so that they get displayed on the screen.
    Hope this helps. Reward points for useful answers.
    Regards
    Nithya

  • How to truncate the values from the table

    Hi All,
    I am working on an issue..where we are first deleting all the records from the table and then based on few conditions we are putting the records back in that table...when we tried to run this program along with few others those who are doing almost the same stuff we are having issues...we tried to schedule few jobs related to these programs only...but after a ceratin amount of time couple of jobs got canceled...I was talking to my basis guy and he said the problem is ratehr then truncating the records from the table we are deleting the records and it's taking lots and lots of space to execute...so we need to truncate the records from the table insted of deleting it...we are using the following the statement right now:
        DELETE FROM ZTUS_PG.
        COMMIT WORK.
    So can you please tell me how can we truncate the values from this table instead of just deleting them and what would be effect of this.
    Thanks,
    Rajeev Gupta

    I don't think basis is saying you should delete all the records from the table. They are saying remove the table and it's contents (a much faster thing to do). I'm not sure this the right thing to do, but you can have a look at:
    http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.apdv.sample.doc/doc/admin_scripts/s-truncate-db2.htm
    Something like:
    EXEC SQL.
      TRUNCATE TABLE ZTUS_PG REUSE STORAGE
    ENDEXEC.
    COMMIT WORK.                      "Empty table is committed here
    Rob
    Edited by: Rob Burbank on Dec 1, 2008 4:06 PM

  • Short Dump while fetching values from a Database view

    Hi ALL,
    Here is the code that is giving short dump
    SELECT * FROM ZVMATLMOVE INTO TABLE I_MATLMOVE
        WHERE BUDAT >= V_LASTRUN_DATE
        AND   WERKS IN S_WERKS
        AND   LIFNR IN S_LIFNR
        AND   EBELN IN S_EBELN
        AND   MATNR IN S_MATNR
        AND   BWART IN S_BWART
    (Please don't say that I am using * in the select query,
    I knew that it is not a good way of fetching values)
    Declaration of the internal table is:
    DATA  I_MATLMOVE LIKE ZVMATLMOVE OCCURS 0 WITH HEADER LINE.
    The variable V_LASTRUN_DATE is:
    DATA  V_LASTRUN_DATE LIKE SY-DATUM.
    We will be getting the lastrundate value from another table. And it is passing correct value (ex. 20060731)
    ZVMATLMOVE is a database view created for MKPF and MSEG table. And I checked both table were consistent.
    Dump Analysis:
    Runtime errors         DBIF_RSQL_SQL_ERROR          
    Exception              CX_SY_OPEN_SQL_DB
    Every thing is fine. But I don't know how it is going to dump. Any suggestions?

    Hi !
    It seams that your table is not correct / fully activated.
    To check it out you should try the following:
    - Go to the SE11
    - Give it your table name and go to "Display"
    - Check if the table is "active"
    - Choose "Utilities->Database Object->Check" and see
      if there are any errors
    - go back and choose "Utilities->Runtime Object->Check"
      and see if there are any errors
    If there are any errors - try to activate the table again. You may need the "Utilities->Database Utiliy" for that.
    After there are no more errors by checking all these your program should work.
    Regards
    Rainer
    Some points would be nice if thate helped a bit.

  • Get value from the array based on the HashCode

    public static void runJoin(int[][] t1,int[][] t2)
         PrintWriter out=null;
         int rows = 1000;
         int cols = 7;
         int [][] myTable3 = new int[rows][cols];
         int x = 0;
         System.out.print("Running HashJoin:Method loads the "+
         "smaller table in the memory and applies a hashing function "+
         "to common column and stores it in another table. "+
         "The larger table is then read from the file. "+
         "The same hashing function is applied to Col n of the table and a       matching record in the first table is looked up. A match will create a row in Table 3. ");          
    //Apply hashing function to smaller table and store it in the memory.
              Integer[] It2 = new Integer[t2.length];
              int [] hashCodest2 = new int[t2.length];
              Hashtable ht = new Hashtable();
              for(int i =0; i <t2.length;i++){
                   It2[i] = new Integer(t2[0]);
                   hashCodest2[i] = It2[i].hashCode();
                   ht.put(new Integer(hashCodest2[i]),It2[i]);
              //Larger table get hashcodes
              Integer It1[] = new Integer[t2.length];
              int [] hashCodest1 = new int[t2.length];          
              for(int j =0; j <t1.length;j++){
                   It1[j] = new Integer(t1[j][4]);
                   hashCodest1[j] = It1[j].hashCode();               }
              //Based on the hashcode get the value from the Table2;
              try{
    out = new PrintWriter( new FileOutputStream( "c:\\HashJoinTable.txt" ) );
              Enumeration e = ht.keys();
                   while(e.hasMoreElements())
    //How do I get the value from the array based on the HashCode? Do I need to do a loop here???                         
    hashCodes1.get(e.nextElement());           
              }catch(Exception e){}

    ok I got it......
              //Apply hashing function to smaller table and store it in the memory.
              Integer[] It2 = new Integer[t2.length];
              int [] hashCodest2 = new int[t2.length];
              Hashtable ht = new Hashtable();
              for(int i =0; i <t2.length;i++){
                   It2[i] = new Integer(t2[0]);
                   hashCodest2[i] = It2[i].hashCode();
                   ht.put(new Integer(hashCodest2[i]),It2[i]);
              //Larger table get hashcodes and compare
              Integer It1[] = new Integer[t2.length];
              int [] hashCodest1 = new int[t2.length];          
              Hashtable ht2 = new Hashtable();
              for(int j =0; j <t1.length;j++){
                   It1[j] = new Integer(t1[j][4]);
                   hashCodest1[j] = It1[j].hashCode();               
                   ht2.put(new Integer(hashCodest1[j]),It1[j]);
              //Based on the hashcode get the value from the Table2;
              try{
    out = new PrintWriter( new FileOutputStream( "c:\\HashJoinTable.txt" ) );
              Enumeration e = ht.keys();
              Integer t3[] = new Integer[t2.length];
                   while(e.hasMoreElements())
                        t3[x] = (Integer) ht2.get(e.nextElement());                
                        x++;
              }catch(Exception e){}

Maybe you are looking for