Creating View based on Current and previous data from same table

I am trying to create a view based on a table called “my_companies”. The table has following columns: “company_id”, “start_date”, “product_type_code”, “partner_id”
The main purpose of this view is to obtain previous company_id’s associated with a particular “partner_id“and “product_type_code”. So basically, I’m looking to create an extra column, say “prev_company_id” in the view along with all the other columns. The “previous” data can be obtained depending on the “start_date”. I’m not able to write a query successfully to do this.
Can anyone help? Thanks in advance.

Hi,
Whenver you have a question, it helps to post:
(1) The version of Oracle (and any other relevant software) you're using
(2) A little sample data (just enough to show what the problem is) from all the relevant tables
(3) The results you want from that data
(4) Your best attempt so far
Executable SQL statements (like "CREATE TABLE AS ..." or "INSERT ..." statements) are best for (2).
Formatted tabular output is okay for (3). Type before and after the tabular text, to preserve spacing.  The sample results should include any special cases that you foresee, such as one company having many previous companies, or vice-versa.
It sounds like might need a +self-join+, where you have two copies of the same table, as if the current companies were in one table and the previous companies were in another, even though they are all actually in the same table.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • Creating a external content type for Read and Update data from two tables in sqlserver using sharepoint designer

    Hi
    how to create a external content type for  Read and Update data from two tables in  sqlserver using sharepoint designer 2010
    i created a bcs service using centraladministration site
    i have two tables in sqlserver
    1)Employee
    -empno
    -firstname
    -lastname
    2)EmpDepartment
    -empno
    -deptno
    -location
    i want to just create a list to display employee details from two tables
    empid firstname deptno location
    and same time update  in two tables
    adil

    When I try to create an external content type based on a view (AdventureWorks2012.vSalesPerson) - I can display the data in an external list.  When I attempt to edit it, I get an error:
    External List fails when attached to a SQL view        
    Sorry, something went wrong
    Failed to update a list item for this external list based on the Entity (External Content Type) 'SalesForce' in EntityNamespace 'http://xxxxxxxx'. Details: The query against the database caused an error.
    I can edit the view in SQL Manager, so it seems strange that it fails.
    Any advice would be greatly GREATLY appreciated. 
    Thanks,
    Randy

  • Help with writing and retrieving data from a table field with type "LCHR"

    Hi Experts,
    I need help with writing and reading data from a database table field which has a type of "LCHR". I have given an example of the original code but don't know what to change it to in order to fix it and still read in the original data that's stored in the LCHR field.
    Basically we have two Function modules, one that saves list data to a database table and one that reads in this data. Both Function modules have an identicle table which has an array of fields from type INT4, CHAR, and type P. The INT4 field is the first one.
    Incidentally this worked in the 4.7 non-unicode system but is now dumping in the new ECC6 Unicode system.
    Thanks in advance,
    C
    SAVING THE LIST DATA TO DB
    DATA: L_WA(800).
    LOOP AT T_TAB into L_WA.
    ZDBTAB-DATALEN = STRLEN( L_WA ).
    MOVE: L_WA to ZDBTAB-RAWDATA.
    ZDBTAB-LINENUM = SY-TABIX.
    INSERT ZDBTAB.
    READING THE DATA FROM DB
    DATA: BEGIN OF T_DATA,
                 SEQNR type ZDBTAB-LINENUM,
                 DATA type ZDBTAB-RAWDATA,
               END OF T_TAB.
    Select the data.
    SELECT linenum rawdata from ZDBTAB into table T_DATA
         WHERE repid = w_repname
         AND rundate = w_rundate
         ORDER BY linenum.
    Populate calling Internal Table.
    LOOP AT T-DATA.
    APPEND T_DATA to T_TAB.
    ENDLOOP.

    Hi Anuj,
    The unicode flag is active.
    When I run our report and then to try and save the list data a dump is happening at the following point
    LOOP AT T_TAB into L_WA.
    As I say, T_TAB consists of different fields and field types whereas L_WA is CHAR 800. The dump mentions UC_OBJECTS_NOT_CONVERTIBLE
    When I try to load a saved list the dump is happening at the following point
    APPEND T_DATA-RAWDATA to T_TAB.
    T_DATA-RAWDATA is type LCHR and T_TAB consists of different fields and field types.
    In both examples the dumps mention UC_OBJECTS_NOT_CONVERTIBLE
    Regards
    C

  • Loading masterdata and transaction data from same flat file

    hi all,
    how can i load master data and transaction data from the same flatfile at a time.

    I am afraid it is possible.
    Go thru this Uploading Master & Transaction Data together from Flat File

  • I am trying to gather date and cost data from one table to another:

    Appreciate some help on this one.
    I have two tables.
    Table One showing a number of columns; including column 'F' Expiry / Renewal and column 'I' Charge (in £s)
    On Table Two I have 5 columns where each column represents a year (2011, 2012 etc) and 12 Rows, each representing the 12 Months (January, December etc)
    I was hoping to gather the Charge information on Table Two by using the following; changing the month and year after the "= as necessary
    =SUMIF('Expires / Renewal',"=November 2011",(Gross charge))
    The problem I have is that column F in Table One is shown as dd month yyyy (15 July 2011) and Table Two will only calculate those months in column F Table One if the day recorded is the first of the month. For example: 1 November 2011 (NOT 01 November 2011).
    You will be able to see from my screen capture of Table Two that there is a discrepancy between my 'Check Totals' column B and Column C. Column B has been calculated manually including all day ranges per month from 1st - 31st. Column C has been auto calculated by using variations of the formula above (per row) but is only picking up those dates with the first being recorded.
    NB: My fanancial year runs from Oct - Sept hence the layout attached. I am also in the UK hence the date format. Using Numbers 09
    Thanks in advance.
    Glen

    Glen,
    Here's a suggestion you can think about, after which you can work out the details. If you need more help, just ask.
    I would add a column, say Column J, to your data table (first table), hide later, that has the following expression to create a date code for your SUMIF expression to use as a condition.:
    =MONTH(F)&"-"&YEAR(F)
    Your summary then could use the expression shown in this screen shot, if you were to use a calendar year approach, and a modified expression for your fiscal year, which you may work out on your own:
    Regards,
    Jerry

  • Getting the previous data from The table....

    Hi,
    I have a tble in my schema. I have to run the process everday and it updates the table and commits the data.
    My question is ......can i get the data back which was there before i ran the process....simple way ...can i get the data back after commiting ...????
    Thank you guys.... I really appriciate if you could answer.....Thank you

    other useful link
    http://www.oracle.com/technology/products/oracle9i/daily/apr18.html
    This today post is related..
    Flashback.....Help
    Edited by: dask99 on Oct 21, 2008 5:29 PM

  • Copying and updating Data  from a table to new table using Merge command

    Hi ,
    Can anyone please tell me how to do this?
    I have a table : EMP(empno(pk),ename,sal,dept) another table is EMP_CLASS(empno(pk),ename)
    I want to insert corresponding rows from emp to emp_class table if that row does'nt exist in emp_class
    otherwise it will update corrsponding info in emp_class table as well as delete from emp_class according to emp delete operation.
    Thanks ,
    Deekay.
    Edited by: Deekay on Aug 12, 2010 10:59 PM

    Hi Vishu,
    This is really helpful, but I want little modification like it will check for deptno in emp and insert in class field if dept is 10 then 1 ,20 ,2 like wise. I have changed emp_class structure .Please find my updated code eaccording to that ,but I am getting error.
    MERGE
    INTO emp_class
    USING emp
    ON  (emp.empno = emp_class.empno)
    WHEN MATCHED
    THEN
    UPDATE
    SET emp_class.ename = emp.calss_name,
        emp_class.deptno = emp.deptno,
        emp_class.class=select decode(deptno,10,1,20,2,30,3,40,4)from emp
    DELETE
    WHERE emp_class.empno = emp.empno
    WHEN NOT MATCHED
    THEN
    INSERT (emp_class.empno,emp_class.name,emp_class.deptno,emp_class.class)
    VALUES (emp.empno,emp.name,emp.sal,emp.deptno,decode(deptno,10,1,20,2,30,3,40,4)emp.class);
        Please help me to fix this.
    this is the error:
    MERGE
    INTO emp_class
    USING emp
    ON (emp.empno = emp_class.empno)
    WHEN MATCHED
    THEN
    UPDATE
    SET emp_class.ename = emp.calss_name,
    emp_class.deptno = emp.deptno,
    emp_class.class=select decode(deptno,10,1,20,2,30,3,40,4)from emp
    DELETE
    WHERE emp_class.empno = emp.empno
    WHEN NOT MATCHED
    THEN
    INSERT (emp_class.empno,emp_class.name,emp_class.deptno,emp_class.class)
    VALUES (emp.empno,emp.name,emp.sal,emp.deptno,decode(deptno,10,1,20,2,30,3,40,4)emp.class);

  • Fetch data from same table

    Hi All,
    Oracle 10g
    The data in cust_link_tab is of 2 systems. Internal and External.
    I want to compare fields (date, ccy, type) of the below table on the basis of linking id.
    currently i am using a query like this:
    SELECT F.SOURCE,
    case
         when fac.type = f.type then
         'Y'
         else 'N'
    end fac_cusip
    FROM cust_link_tab FAC, cust_link_tab F
    WHERE
    FAC.LINKING_ID = F.LINKING_ID
    AND FAC.ROWID!=F.ROWID;
    But if there is more than one linking_id. this won't work correctly.
    SQL> DESC CUST_LINK_TAB;
    Name Null? Type
    FSRC_ID VARCHAR2(10)
    SOURCE VARCHAR2(10)
    DSRCL_ID VARCHAR2(10)
    CCY VARCHAR2(3)
    MATURITY_DATE DATE
    GLOBAL_CMT NUMBER
    LINKING_ID NUMBER
    TYPE VARCHAR2(10)
    SQL> select *from CUST_LINK_TAB;
    FSRC_ID SOURCE DSRCL_ID CCY MATURITY_ GLOBAL_CMT LINKING_ID TYPE
    111 INTERNAL 900 usd 1000 ER
    45 EXTERNAL 600 usd 1000 TR
    454 INTERNAL 700 usd 500 II
    SQL>
    Thanks.
    Edited by: user545846 on May 9, 2009 10:17 PM

    SQL> select *from CUST_LINK_TAB;
    FSRC_ID SOURCE DSRCL_ID CCY MATURITY_ GLOBAL_CMT LINKING_ID TYPE
    111 INTERNAL 900 USD 1000 ER
    45 EXTERNAL 600 USD 1000 TR
    454 INTERNAL 700 USD 500 II
    32 INTERNAL 300 EUR 25 2885 PO
    96 EXTERNAL 600 USD 434 2885 PO
    Basically we need to compare the fields ccy, global_cmt,type for internal and external
    source.
    Linking id is used to link the data. we are expecting the fsrc_id,source,dsrcl_id and result whether 'Y' or 'N' which we can do using a decode or case statement.
    source, fsrc_id and dsrcl_id are the primary keys (composite) for this table (cust_link_tab).
    Apart from this we have the map table which keeps the fsrc_id, dsrcl_id, dsrcl_id of the
    internal system and the corresponding external fsrc_id and dsrcl_id. The data is loaded using
    the linking_id.
    But this table does not maintain the details like ccy, maturity date, and type.
    Please give your suggestions. thanks

  • SQL Select Performance - Approached to fetch data from big table

    Hi
    I just wanted to know view on different approached to fetch data from a table which has 40 billion records and which joined to another table which has 1 million record.
    e.g.
    I have two tables TableA and TableB
    TableA has 40 Billion records has 6 columns
         TableA has partitions on Date
         TableA has required indexes
    TableB has 1 Milluion record and has 10 columns
         Table A has indexes
    Now I have written query like
    select distinct TableA.column1,TableA.column2,TableB.columnA
    FROM TableA join TableB
    ON TableA.Column1=TableB.Column2
    WHERE TableA.DateColumn between StartDate and EndDate
    for a given date range it will fetch 5 billion of records which takes around 40 minutes.
    I just wanted to know what all tuning approaches I can follow. What would be the best approach to make record retrieval faster in such a scenario.
    Just wanted to know your vies/experience in such a scenario

    Sufficiently large array fetchsize
    and,
    possibly using parallel query,
    pop into my mind.
    I would be interested though in the business requirement that asks for you to write a program that gets 5 billion (!) rows out of the database...

  • How to retrieve data from edcauditentity table?

    Hello!
    I am interested how to connect to edcauditentity table and retrieve data from this table.
    I have sql query but i don't have idea how to start. For now i can connect to LiveCycle and retrieve policy name.
    Thank in advance!

    Hello Mohan,
    if u already have data and u want to populate it in F4 help then use below code -
    u Have to make use of FM - 'F4IF_INT_TABLE_VALUE_REQUEST'
    REPORT  ZGILL_VALUE_REQUEST                     .
    data: begin of lt_all occurs 0.
            include structure DYNPREAD.
    data  end of lt_all.
    data: begin of lt_selected occurs 0.
           include structure DDSHRETVAL.
    data: end of lt_selected.
    DATA: BEGIN OF lt_code OCCURS 0,
                code LIKE zgill_main-PERNR,
          END OF lt_code.
    data no_dyn like sy-dynnr.
    Parameters : ECODE like zgill_main-PERNR.
    *parameters: pernr like pa0001-pernr .
    no_dyn =  sy-dynnr.   "give the scren no directly or sy-dynnr in case of report.
    At selection-screen on value-request for ECODE.
    select PERNR into table lt_code from zgill_main.
      CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
          EXPORTING
            retfield               = 'ECODE'
            dynpprog               = sy-repid
           dynpnr                  = no_dyn
          dynprofield              =       'ECODE'
          window_title           = 'Employee Details'
           value_org              = 'S'
          DISPLAY                = 'F'
       TABLES
            value_tab             = lt_code
           RETURN_TAB             = lt_selected.
    EXCEPTIONS
      PARAMETER_ERROR        = 1
      NO_VALUES_FOUND        = 2
      OTHERS                 = 3
    *if sy-subrc eq '0' .
      write: 'success'.
    *endif.
    read   table lt_selected index sy-tabix.
    move lt_selected-fieldval to ECODE.

  • Difference between current row and previous row in a table

    Hi All,
    I am having a problem with the query. Can some of please help me?
    I need to get difference between current row and previous row in a table. I have a table, which have data like bellow.
    TABLEX
    ================
    Name Date Items
    AAA 01-SEP-09 100
    BBB 02-SEP-09 101
    CCC 03-SEP-09 200
    DDD 04-SEP-09 200
    EEE 05-SEP-09 400
    Now I need to get output like bellow...
    Name Date Items Diff-Items
    AAA 01-SEP-09 100 0
    BBB 02-SEP-09 101 1
    CCC 03-SEP-09 200 99
    DDD 04-SEP-09 200 0
    EEE 05-SEP-09 400 200
    Can some one help me to write a query to get above results?
    Please let me know if you need more information.
    Thanks a lot in advance.
    We are using Oracle10G(10.2.0.1.0).
    Thanks
    Asif

         , nvl (items - lag (items) over (order by dt), 0)like in
    SQL> with test as
      2  (
      3  select 'AAA' name, to_date('01-SEP-09', 'dd-MON-rr') dt,  100 items from dual union all
      4  select 'BBB' name, to_date('02-SEP-09', 'dd-MON-rr') dt,  101 items from dual union all
      5  select 'CCC' name, to_date('03-SEP-09', 'dd-MON-rr') dt,  200 items from dual union all
      6  select 'DDD' name, to_date('04-SEP-09', 'dd-MON-rr') dt,  200 items from dual union all
      7  select 'EEE' name, to_date('05-SEP-09', 'dd-MON-rr') dt,  400 items from dual
      8  )
      9  select name
    10       , dt
    11       , items
    12       , nvl (items - lag (items) over (order by dt), 0)
    13    from test
    14  ;
    NAM DT             ITEMS NVL(ITEMS-LAG(ITEMS)OVER(ORDERBYDT),0)
    AAA 01-SEP-09        100                                      0
    BBB 02-SEP-09        101                                      1
    CCC 03-SEP-09        200                                     99
    DDD 04-SEP-09        200                                      0
    EEE 05-SEP-09        400                                    200
    SQL>

  • Is this a bug? create view lost a comma and succeeded

    Is this a bug? create view lost a comma and succeeded.
    oracle 10.2.0.1.0
    try the following sql.
    create table test
    id int,
    dataa varchar2(20),
    datab varchar2(20)
    insert into test values(1,'a1','a2');
    insert into test values(2,'b1','b2');
    insert into test values(3,'c1','c2');
    create view vtest
    as
    select id,dataa
    datab
    from test;
    --it should be error but successed
    select * from vtest;
    --and dataa gone!
    drop view vtest;
    drop table test purge;

    No it's not a bug, Oracle will treat "datab" as alias to "dataa" if comma left out.
    Doesn't your view has two columns id and datab, but datab column showing dataa data?

  • Report that display 'Net Pay' by Empl for current and previous period.

    Hi,
    We are looking for a SAP report that display 'Net Pay' by Employee for current and previous period in USA payroll module. If you know of any, pl let me know.
    Thanks in advance,
    Niranjan

    Thanks Archana and Sikindar.
    We knew about this report, however, it gives information one below the other if we run, say for 2 periods, but what we are looking for is something as shown in example below
    Empl #      Empl # Name    Prev Pay period Net Pay        Current Pay period net pay.
    123              XYZ                     $ 1200.00                                 $ 1200.00
    256              ABC                    $  2000.00                                $ 3000.00 
    We want to run for 2 periods at a time and get the results as above. That way, payroll dept can run this report and compare if we are paying too much in current pay, compared to previous pay. This is basically to avoid any typos when they create new pay records in infotype 0008.
    Niranjan

  • Adding rows based on current and next row

    I got some excellent help on multiplying rows based on start and end date in this
    thread, resulting in the query below. It helps me follow Vehicle activity and Vehicle allocation of our vehicles day by day. Now I would like to add another feature to the query, if it is possible.
    The problem is that in our database, only actual tasks are registered, which means that the time when the vehicle is between tasks is not showing. I could of course calculate total available time per vehicle and month, but that would not tell me where the
    vehicles are waiting, when during the day, etc.
    So I would like to insert rows for when the vehicles are standing still, and the logic would be something like this:
    If vehicle number on current row equals vehicle number on the next row and End (date/time) of current row < Start (date/time) of next row, insert row after current row. Set Start=End of current row and End=Start of next row. Set From=To
    of current row and To=To of current row. Set Vehicle activity to "Not active". Finaly copy all other fields from current row.
    Is this possible to achieve in Power Query?
    Brgds,
    Caj
    let
        Source = Sql.Databases("sql10"),
        SLM = Source{[Name="SLM"]}[Data],
        dbo_V_LKPI = SLM{[Schema="dbo",Item="V_LKPI"]}[Data],
        RenamedColumns = Table.RenameColumns(dbo_V_LKPI,{{"ActualDeparture", "Start"}, {"ActualArrival", "End"}}),
         Records = Table.ToRecords(V_LocoKPI),
          DateTime.IsSameDay = (x, y) => Date.Year(x) = Date.Year(y) and Date.Month(x) = Date.Month(y) and Date.Day(x) = Date.Day(y),
          Expand = (x) => List.Generate(
              () => Record.Combine({x, [End=Date.EndOfDay(x[Start])]}),
              (record) => record[Start] <= x[End],
              (record) => let
                  NextStart = Date.StartOfDay(Date.AddDays(record[Start], 1)),
                  NextEnd = Date.EndOfDay(NextStart),
                  ThisEnd = List.Min({NextEnd, x[End]})
              in
                  Record.Combine({record, [Start=NextStart, End=ThisEnd]})),
          Transformed = List.Transform(Records, each if DateTime.IsSameDay([Start], [End]) then {_} else Expand(_)),
          Combined = List.Combine(Transformed),
          Result = Table.FromRecords(Combined)
      in
          Result
    Csten

    Here's some sample code. Again, we use List.Generate to build either a record or a list of records and then use List.Combine to bring the results back together before converting them to a table.
    let
        CombineTwoRows = (x, y) =>
            let
                combine = x[Vehicle] = y[Vehicle] and x[End] < y[Start],
                added = Record.Combine({x, [Start=x[End], End=y[Start], Active=false]}),
                result = if combine then {added, y} else {y}
            in result,
        GenerateStandingRows = (table, combine) =>
            let
                Handle = (x, y) => {x, y},
                buffered = Table.Buffer(table),
                n = Table.RowCount(buffered),
                windows = List.Generate(
                    () => {1, {buffered{0}}},
                    (x) => x{0} <= n,
                    (x) => {x{0} + 1, if x{0} < n then combine(buffered{x{0}-1}, buffered{x{0}}) else {buffered{x{0}}}},
                    (x) => x{1})
            in
                windows,
        InsertInactivity = (table) => Table.FromRecords(List.Combine(GenerateStandingRows(table, CombineTwoRows))),
        TestData = Table.FromRows({
            {1, #datetime(2014, 2, 23, 13, 0, 0), #datetime(2014, 2, 23, 13, 10, 0), true},
            {1, #datetime(2014, 2, 23, 13, 20, 0), #datetime(2014, 2, 23, 13, 30, 0), true},
            {2, #datetime(2014, 2, 23, 13, 20, 0), #datetime(2014, 2, 23, 14, 0, 0), true},
            {2, #datetime(2014, 2, 23, 14, 20, 0), #datetime(2014, 2, 23, 14, 40, 0), true},
            {2, #datetime(2014, 2, 23, 16, 0, 0), #datetime(2014, 2, 23, 17, 0, 0), true},
            {2, #datetime(2014, 2, 24, 2, 0, 0), #datetime(2014, 2, 24, 3, 0, 0), true},
            {3, #datetime(2014, 2, 24, 1, 0, 0), #datetime(2014, 2, 24, 8, 0, 0), true},
            {3, #datetime(2014, 2, 24, 9, 0, 0), #datetime(2014, 2, 24, 10, 0, 0), true}
            }, {"Vehicle", "Start", "End", "Active"})
    in
        InsertInactivity(TestData)

  • LineChart with current and historical data daily report

    Hi all,
    I'm new on BAM and I want to know if it is possible to define a LineChart showing information about today and the 30 last days.
    Is it possible using two dataobjects, one for today data and an external one provided by ODI with the contents for the last 30 days?
    Anyone can provide a sample?
    Thanks in advance.

    Hi,
    Both current and historical data are always stored within the same table. There is no option to create separate tables for each that are managed by OWM.
    However, you do have the option to use dbms_wm.PurgeTable which can be used to purge a set of data, and optionally store it in a archive table. But, after that is done the data is no longer under Workspace manager's control or the versioning environment. From the description that you gave, I am unsure if this would be sufficient to satisfy your requirements. I am guessing not, but wanted to make you aware of the functionality.
    Regards,
    Ben

Maybe you are looking for