Selection of records in the same table problem

Hi all

I have the following table
with emp as (
           select '11' A,'aaa' B, '40' C from dual union all
           select '11','bbb', '40' from dual union all
           select '33','ccc', '30' from dual union all
           select '44','ddd', '20' from dual union all
           select '11','eee', '10' from dual
          )
My results should be
A           B        C
 
11        aaa      40
11        bbb     40      
11        eee     10
Basically the requirement is select different combination of values in the column 'B' need to know what is the value of 'A' (it must be the same for all records of three)


Hope in this sense.


See you soon

Sexy

an attempt to rephrase:

you want all the files "aaa", "bbb" and "EEA" where, for each set of column A, where they exist.

that is, if games to have only "aaa" and "bbb" but not "eee" in column B, then you don't want to retrieve this record?

Try this:

SQL> with emp as (
  2  select '11' A,'aaa' B, '40' C from dual union all
  3  select '11','bbb', '40' from dual union all
  4  select '33','ccc', '30' from dual union all
  5  select '44','ddd', '20' from dual union all
  6  select '11','kkk', '20' from dual union all
  7  select '10','eee', '20' from dual union all
  8  select '11','eee', '10' from dual
  9  )
 10  select a, b, c
 11   from (select emp.*, count(*) over (partition by a) cnt
 12    from emp
 13   where b in ('aaa','bbb','eee'))
 14   where cnt = 3
 15  /

A                                B                                C
-------------------------------- -------------------------------- --------------------------------
11                               eee                              10
11                               aaa                              40
11                               bbb                              40

3 rows selected.

Published by: WhiteHat June 30, 2011 11:04

Tags: Database

Similar Questions

  • Compare the records from the same table

    Hi all

    I have this sample, the data were rendered are group by my_id, the same number of records exist for the two my_ids (2 and 62) as:

    create table myTest as
    (
    my_id number, 
    fieldA varchar2, 
    fieldB number, 
    fieldC number, 
    cost_A number, 
    cost_B number
    )
    
    insert into myTest (my_id, fieldA, fieldB, fieldC, cost_A, cost_B)
    values (2, 'MAINT', 60, 5, 10.3, 15.00);
    insert into myTest (my_id, fieldA, fieldB, fieldC, cost_A, cost_B)
    values (2, 'MAINT', 70, 6, 20.3, 25.00);
    insert into myTest (my_id, fieldA, fieldB, fieldC, cost_A, cost_B)
    values (2, 'MAINT', 80, 7, 30.3, 35.00);
    insert into myTest (my_id, fieldA, fieldB, fieldC, cost_A, cost_B)
    values (62, 'MAINT', 60, 5, 10.3, 5.00);
    insert into myTest (my_id, fieldA, fieldB, fieldC, cost_A, cost_B)
    values (62, 'MAINT', 70, 6, 20.3, 25.00);
    insert into myTest (my_id, fieldA, fieldB, fieldC, cost_A, cost_B)
    values (62, 'MAINT', 80, 7, 10.3, 15.00);
    

    How can display the records with numbers of different costs for the same unique key (fieldA, fieldB and FieldC)?

    With the help of Oracle Database 11 g Enterprise Edition Release 11.2.0.4.0.

    I hope that my message is clear.

    Thank you!

    Hello

    user9542267 wrote:

    ... I need all the exits...

    Me too.  Always show the complete, accurate, results you want from the data provided.  If you want 2 rows at the exit point, don't tell you want 1.

    Here are the results you want?

    MY_ID FIELDA, FIELDB, FIELDC OLD_COST_A COST_A OLD_COST_B COST_B

    ------ ---------- ------ ------ ---------- ------ ---------- ------

    MAINT 62 60 5 10.3 10.3 15 5

    MAINT 62 80 7 30.3 10.3 35 15

    If so, here's a way to get them:

    WITH got_old_costs AS

    (

    SELECT fielda, fieldb, fieldc, cost_a, my_id, cost_b

    , LAG (cost_a) OVER (PARTITION BY fielda, fieldb, fieldc)

    ORDER BY my_id

    ) AS old_cost_a

    , LAG (cost_b) OVER (PARTITION BY fielda, fieldb, fieldc)

    ORDER BY my_id

    ) AS old_cost_b

    OF mytest

    WHERE my_id IN (2, 62)

    )

    SELECT my_id, fielda, fieldb, fieldc

    old_cost_a, cost_a

    old_cost_b, cost_b

    OF got_old_costs

    WHERE my_id = 62

    AND (cost_a <> old_cost_a)

    OR cost_b <> old_cost_b

    )

    ORDER BY fielda, fieldb, fieldc

    ;

  • Compare several records in the same table

    Hello, I m writing a bat file so I can export information that I question.

    I have an automatic integration which checks from time to time if there is no new client´s and generates a trigger.
    If an error levonorgestrol I the process is repeated until the client is located in the database.
    I can't create tables or change the structure.


    My problem is that I need to compare the record more updated with the CLIENT_ID field
    Let me give you an example:


    Table A

    ERROR_MESSAGE CREATEDUSERID CLIENT_ID
    0 success 01/01/2009
    1 error 01/01/2009
    2 success 01/01/2009
    1 success 01/02/2009
    3 success 01/02/2009
    4 error 01/02/2009

    I need to compare "1" client created on 01/01/2009 this error gived with new records to see if there's success and my
    query should only return the client_ID '4' and export with sqlplus

    Could you please help me?

    Hello

    It works very well with my data.
    What data do you use? After a few lines of sample data (CREATE TABLE AS executable... or INSERT... statements are best) that give you wrong results.

    Make sure that everything is spelled correctly.
    For example, roughly halfway through the query, you say

    and io.status = 'Erro' 
    

    and at the end you say

    having max(decode(io.status, 'Error', 1, 2))  ...
    

    That is the same ("Error" or "Error") in both places?

  • problem of query by comparing records from the same table against each other

    Hi, i'ms truggling to see where I am going wrong here. I have data from cards of following music: -.
    with charts_table as (select 1 id,'oasis' product_name,0801 week, 20 week_chart_position, 20 highest_chart_position from dual
    union select 2,'oasis',0802,14,14 from dual
    union select 3,'oasis',0803,17,14 from dual
    union select 4,'oasis',0804,29,14 from dual
    union select 5,'kings of leon',0801,55,55 from dual
    union select 6,'kings of leon',0802,22,22 from dual
    union select 7,'kings of leon',0803,35,22 from dual
    union select 8,'kings of leon',0804 , 11 , 11  from dual
    union select 9,'bob dylan',0801, 88 , 88  from dual
    union select 10,'bob dylan',0802,79 , 79  from dual
    union select 11,'bob dylan',0803,54,54 from dual
    union select 12,'bob dylan',0804,22,22 from dual
    union select 13,'kid rock',0801,19,19 from dual
    union select 14,'kid rock',0802,24,19 from dual
    union select 15,'kid rock',0803,55,0 from dual
    union select 16,'kid rock',0804,44,0 from dual)
    italic , I need to identify the rogue data where the highest_position is incorrectly registered lower or 0 as there
    position of the highest week was at an earlier date. (stick with me) for example in this kid of rock data initially charted at position 19. What follows
    week (0802) his week_chart_position slipped to 24 and the position the highest card is correctly saved at 19 (ie the week 1). The problem
    is available in week 0803 and 0804 when somehow the data was corrupted and the higest_chart_position is trying to read 0 (instead of 19). How can I write a query to identify this error?

    is the best I have at the moment:-
    select * from charts_table ct1 where 
    nvl2(highest_chart_position,0,99999)>
    (select min(week_chart_position) from charts_table ct2
    where ct2.week<ct1.week
    and ct1.product_name=ct2.product_name)
    but it's not working. can someone help and tell where I'm wrong. Thanks a lot for the research/resolve.

    Ahh, I was suggesting using the lag function to ensure that highest chart position is not fall lower than highest prior chart positions. Your concern is he reports a higher chart position that she never had. In this case I use the MIN function as an analytic function rather than as an aggregate function:

    with t1 as (
      select ct.*
           , min(week_chart_position) over( PARTITION by product_name order by week) highest
        from charts_table ct
       order by product_name, week
    )
    select * from t1 where highest != highest_chart_position;
    

    Conversely, you place your order of cards, which is the highest rank is 1, thew me. I saw the high word and the expected value in the highest chartposition column to be on the rise, but has seen examples of it decreases. It was an oversight on my part.

    Published by: Sentinel on October 9, 2008 08:31

  • parents and children of the same table records

    I want to create a query that is a union such that 2nd resultset is based on the game of results 1. I have a table that has parent and child records in the same table.

    Table: EVENTS
    EVENT_ID
    PARENT_EVENT_ID
    CREATED_DATE
    (other columns)

    If PARENT_EVENT_ID is null, then this is a parent record, otherwise it is a book of the child. I want to select all parent records then union them with all the related child records... something like this:

    Select * from EVENTS where CREATED_DATE < sysdate - 90 and PARENT_EVENT_ID is null - all parents
    Union
    Select * event where PARENT_EVENT_ID in (select EVENT_ID of EVENTS where CREATED_DATE < sysdate - 90 and PARENT_EVENT_ID is null)-include all children selected from the top parent

    It works but it of kind of ugly, I want to avoid using the subselect in the 2nd because it is a repeat of the 1st statement, is there a way to alias the first statement and only refer to him in the 2nd query?

    Hello

    CONNECTION is very similar to a UNION on the same table. How is this:

    SELECT     *
    FROM     events
    WHERE     created_date     < SYSDATE - 90
    START WITH     parent_event_id     IS NULL
    CONNECT BY     parent_event_id     = PRIOR event_id
         AND     LEVEL          <= 2    -- Maybe
    ;
    

    ?

    To answer your question: Yes, you can still keep the result set of a query and the Treaty as if it were a table or vew, like this:

    WITH     roots     AS
    (
         SELECT     *
         FROM     events
         WHERE     created_date     < SYSDATE - 90
         AND     parent_event_id     IS NULL
    )
    SELECT     *
    FROM     roots
         --
    UNION ALL
            --
    SELECT     *
    FROM     events
    WHERE     created_date     < SYSDATE - 90
    AND     parent_event_id     IN (
                          SELECT  event_id
                          FROM    roots
                      )
    ;
    

    It's always a bit ugly, however. I would use CONNECT BY or from Oracle 11.2, a recursive WITH clause (which is explicitly a UNION), or, in any version, a self-join, like this:

    SELECT     c.*
    FROM          events  c
    LEFT OUTER JOIN     events     p  ON   p.event_id  = c.parent_event_id
    WHERE   p.parent_event_id  IS NULL
    ;
    

    I hope that answers your question.
    If not, post a small example of data (CREATE TABLE and only relevant columns, INSERT statements) for all of the tables involved and the results desired from these data.
    Report where the queriy above (the one you decide to use) is producingthe bad results and explain, using specific examples, how you get the right results from these data in these places.
    Always say what version of Oracle you are using (for example, 11.2.0.2.0).
    See the FAQ forum {message identifier: = 9360002}

  • Support for mandatory request - insert, select from the same table

    Hi all

    I need your help to write queries effectively.
    Oracle Version: 10.2.0.3.0
    OPERATING SYSTEM: UNIX

    I have a METRICS_TBL that is mentioned below table.

    CYCLE_DATE METRIC VALUE
    08/17/2008 COST-TV 100
    08/17/2008 COST-JOURNAL 50
    08/17/2008 COST-POSTALMAIL 25
    08/17/2008-PROD-TV 10
    08/17/2008-PROD-JOURNAL 25
    08/17/2008-PROD-POSTALMAIL 5

    Any data above, I have to add (Insert into select METRICS_TBL METRICS_TBL) at the same table with the records as mentioned below.

    2008-08-17 COSTPERPROD-TV 10
    08/17/2008-COSTPERPROD-LOG 2
    2008-08-17 COST PROD-POSTALMAIL 5

    Basically, I need to calculate the cost per product for each category. Depending on the settings available, metric should also be changed as COSTPERPROD and values should be cost/prod under each category.

    Can someone help me with the query.

    Thank you

    Something like this:

    INSERT INTO metrics_tbl
    (cycle_date, metrics, value)
    SELECT cost.cycle_date
             , 'COSTPERPROD-'||cost.mtype
             ,cost.value / prod.value
    FROM  (
       select cycle_date,substr(metrics, 1, 4) mtype, substrmetrics,instr(metrics,'-')+1) mmetric
       where substr(metrics, 1, 4) = 'PROD'
       ) prod
    INNER JOIN (   select cycle_date,substr(metrics, 1, 4) mtype, substrmetrics,instr(metrics,'-')+1) mmetric
       where substr(metrics, 1, 4) = 'COST'
       ) cost on cost.cycle_date = prod.cycle_date and cost.mmetric = prod.mmetric
    

    Ideally you would divide your METRICS column into two: one for the thing you're measuring (e.g. TV or NEWSPAPER) and the other for the metric (COST, PROD, COSTPERPROD etc.). That's what I did in the views online. Without it, it's kinda a mess and behave so, if the table becomes much more.

    HTH

    Nigel cordially

    Edited by: nthomas on January 14, 2009 15:57 - small correction SQL

  • Copy a few lines in the same table, but with different IDS

    Hi all
    I had this problem... I have a table with its pk (which is a sequence). With a statement select, I extract a few lines, and then I would record in the same table, but with IDS different (obviously eheheh).

    I don't know how to do...

    Thks for all help ;)


    p.s. I want to change some fields in lines before saving as well... don't know how do it more...

    example:

    ID NAME TYPE
    1 ferrari car
    2 cars lamborghini


    I'm trying to copy the second and changing its type in "BMW".

    I could result:

    1 ferrari car
    2 cars lamborghini
    3 bmw cars



    Thank you

    Assuming that your table is named cars_tb and the cars_seq of the sequence.

     insert into cars_tb
      select cars_seq.nextval, name, type
      from cars_tb
    

    This would overlap with any existing lines, but with a new id.

    If you want to duplicate a specific line and change a value, you could do something like:

     insert into cars_tb
      select cars_seq.nextval, name, 'BMW'
      from cars_tb
      where type = 'lamborghini'
    

    or better, use the PK

     insert into cars_tb
      select cars_seq.nextval, name, 'BMW'
      from cars_tb
      where id = 2
    
  • Insert select on the same table: possible without side effects?

    I have a very large table T1 containing millions of records. I need to treat its lines and create a few new lines based on selection.

    Table T1 contains events and one of them, with the code 100, is created by the further development of other events inside the table.

    My code is as follows:

    insert /*+append */ into T1 (code,...) values (100, c1,c2,...)
    select c1,c2... from T1 where (code=20 or code=10) and <other conditions>...
    
    

    as you can see I'm extract T1 lines to insert again in T1 with a different code and I use the direct path in order to get good performance.

    My fear is: choose is made from the same table I risk data loss? In general it is a good practice? Or is it better to create another table?

    Hello

    No I don't think that there may be loss of data. But that may depend on the behavior of the application and your where clause.

    I will explain how it is treated, so you can see if it's ok:

    1. the table is locked because of the insert add, (as)

    2 lines are read by select and make compatible from the State that was at the beginning of the query - 1.

    3 rows are inserted at the end, after the high-water line

    4 columns for new lines are sorted to be merged in the index

    5. high watermark is adjusted - visible new lines and lock is released

    Note that 2. and 3. occur at the same time: rows are inserted all read.

    Note that anyone can choose in the table during the operation - they see the changes committed only - if the State 1.

    all other DML are waiting for the lock being released, and will see new ranks and then

    If you have things that prevent the direct-path insert, append the hint will be ignored. So, if you must rely on close to 1. then the best lock explicitly with table lock. But I don't think that you need.

    Kind regards

    Franck.

  • Sinlge select query in the diff for the same table (same Structure) diagrams

    Scenario:

    Table XYZ is created in detail a.
    After a year, the old data of the previous year could be moved to another schema. However in the other schema of the same table name would be used.

    For example

    A schema contains XYZ table with data from the year 2012
    Schema B contains XYZ table with data for the year 2011
    Table XYZ in the two schemas have an identical structure.

    So we can draw a single select query to read the data from the tables in an effective way.
    For example select * from XYZ so including date between October 15, 2011 to March 15, 2012.
    However, the data resides in 2 different schema altogether.


    Creating a view is an option.
    But my problem, there are ORM (Hibernate or Eclipse Top Link) layer between the application and the database.
    If the queries would be constituted by the ORM layer and are not generated by hand.
    So I can't use the view.
    So is there any option that would allow me to use only query on different scheme?

    970773 wrote:
    Scenario:

    Table XYZ is created in detail a.
    After a year, the old data of the previous year could be moved to another schema. However in the other schema of the same table name would be used.

    For example

    A schema contains XYZ table with data from the year 2012
    Schema B contains XYZ table with data for the year 2011
    Table XYZ in the two schemas have an identical structure.

    So we can draw a single select query to read the data from the tables in an effective way.
    For example select * from XYZ so including date between October 15, 2011 to March 15, 2012.
    However, the data resides in 2 different schema altogether.

    Creating a view is an option.
    But my problem, there are ORM (Hibernate or Eclipse Top Link) layer between the application and the database.
    If the queries would be constituted by the ORM layer and are not generated by hand.
    So I can't use the view.

    Why not make the ORM as below?

    SELECT * FROM VIEW_BOTH;
    -VIEW_BOTH is a real VIEW of Oracle

  • If I have the two LOV in the same table then how to connect when I select first and second LOV value also change?

    Mr President

    If I have the two LOV in the same table then how to connect when I select first and second LOV value also change?

    My two fields are FLOW AND DR_NAME

    FLOW = ACCT_ID

    DR_NAME = ACCT_NAME

    I created with success of LOV for these fields.

    First LOV gives acct_id in the debit field and second LOV gives the value of acct_name to dr_name.

    How can I report these lov, it's that when I change my acct_id then acct_name also change

    I have these two tables

    CREATE TABLE "NOM"  (
      "ACCT_ID" VARCHAR2(7) NOT NULL ENABLE, 
      "ACCT_NAME" VARCHAR2(50) NOT NULL ENABLE, 
      "O_BAL" NUMBER(13,2),
      CONSTRAINT NOM_PK PRIMARY KEY ("ACCT_ID")ENABLE
       
       );
    CREATE TABLE "VOUCHERDET" (
      "V_ID" VARCHAR2(9) NOT NULL ENABLE,
      "LINEITEM" NUMBER ,
      "DEBIT" VARCHAR2(7) , 
      "DR_NAME" VARCHAR2(50), 
      "CREDIT" VARCHAR2(7) , 
      "CR_NAME" VARCHAR2(50), 
      "PARTICULARS" VARCHAR2(100), 
      "AMOUNT" NUMBER(21,2),
    CONSTRAINT VOUCHERDET_PK PRIMARY KEY ("V_ID","LINEITEM")ENABLE, 
    CONSTRAINT PUR_SAL_LINE_POD_FK FOREIGN KEY(PROD_ID)
      REFERENCES PRODUCTS (PROD_ID)ENABLE,  
    CONSTRAINT VOUCHERDET_DEBIT_FK FOREIGN KEY ("DEBIT")
       REFERENCES "NOM" ("ACCT_ID") ENABLE, 
    CONSTRAINT VOUCHERDET_CREDIT_FK FOREIGN KEY ("CREDIT")
       REFERENCES "NOM" ("ACCT_ID") ENABLE,  
    CONSTRAINT VOUCHERDET_V_FK FOREIGN KEY ("V_ID")
       REFERENCES "VOUCHER" ("V_ID") ON DELETE CASCADE ENABLE
      );
    
    

    Concerning

    so, instead of this second ActId, choose ACCT_NAME:

  • place a select query calculation in a different column in the same table

    How can I put my calculation result in a column named within the same table?

    I have a table called: dgpercentagedatachart

    I use the columns of this dgpercentagedatachart: totalcecrating divided by lowestfeederrating times 100 to get the percentage

    In the query, I gave the result the Alias of the cal

    What I want is to put this result in my application or my calculation (in percentage) in my column "percent" on my table of dgpercentagedatachart vacuum.

    How can I configure this syntax?

    This is the select query, I came with:

    Select dgpercentagedatachart.totalcecrating, dgpercentagedatachart.lowestfeederrating,.

    100.00*dgpercentagedatachart.totalcecrating/dgpercentagedatachart.lowestfeederrating as cal

    of dgpercentagedatachart;

    Here are the results:

    CAL lowestfeederrating Totalcecrating

    8,978 7.48166666666666666666666666666666666667 120

    30.951 25.7925 120

    5.04                         120                          4.2

    Hello

    2685870 wrote:

    How can I put my calculation result in a column named within the same table?

    I have a table called: dgpercentagedatachart

    I use the columns of this dgpercentagedatachart: totalcecrating divided by lowestfeederrating times 100 to get the percentage

    In the query, I gave the result the Alias of the cal

    What I want is to put this result in my application or my calculation (in percentage) in my empty column '%' on my table of dgpercentagedatachart .

    How can I configure this syntax?

    This is the select query, I came with:

    Select dgpercentagedatachart.totalcecrating, dgpercentagedatachart.lowestfeederrating,.

    100.00*dgpercentagedatachart.totalcecrating/dgpercentagedatachart.lowestfeederrating as cal

    of dgpercentagedatachart;

    Here are the results:

    CAL lowestfeederrating Totalcecrating

    8,978 7.48166666666666666666666666666666666667 120

    30.951 25.7925 120

    5.04                         120                          4.2

    To change an existing column in a table, you can use the UPDATE or MERGE, instructions like this:

    UPDATE dgpercentagedatachart

    Percentage of VALUE = 100,00 * totalcecrating

    / lowestfeederrating

    ;

    Noramlly, tables is not redundant columns like this.  If percent can always be calculated from other columns, then it is probably better to calculate at run time and store it in the database, where you will have to be updated each time the columns it depends on change.  You can use a view to avoid having to encode them the calculation.

    If you really don't want a column that can be calculated in the same lines other columns, then use a virtual column (if you use Oracle 11 or higher).

    I hope that answers your question.

    If this isn't the case, please post a small example of data (CREATE TABLE and only relevant columns, INSERT statements) for all of the tables involved and also publish outcomes from these data.

    If you ask on a DML statement, such as UPDATE, the sample data will be the content of the or the tables before the DML, and the results will be the State of the or the tables changed when it's all over.

    Explain, using specific examples, how you get these results from these data.

    Always say what version of Oracle you are using (for example, 11.2.0.2.0).

    See the FAQ forum: Re: 2. How can I ask a question on the forums?

  • Updated with the values in the same table, for other records corresponding to conditions

    Hi Experts,

    Sorry do not provide the structure of the table (it is a simple structure)

    I have a requirement where I need to update the columns of a table based on the same table with some match empid and date values. If the date and empid match so I have these values to any other folder and update of one who is not having details of Office . I need the Update query

    Before the update my array of values is as below

    Sort_num Emp_id Bureau start_date

    1 101 AUS 01/01/2013
    2 101 01/01/2013
    3 101 15/01/2013
    4 103 USA 01/05/2013
    5 103 01/01/2013
    6 103 05/01/2013
    7 104 FRA 01/10/2013
    8 104 10/01/2013
    9 104 01/01/2013

    After update my table should be as below

    Sort_num Emp_id Bureau start_date

    1 101 AUS 01/01/2013
    2 101 AUS 01/01/2013
    3 101 15/01/2013
    4 103 USA 01/05/2013
    5 103 01/01/2013
    6 103 USA 01/05/2013
    7 104 FRA 01/10/2013
    8 104 FRA 01/10/2013
    9 104 01/01/2013

    Thanks in advance

    I don't have the time to create the table with the data, but basically, you should be able to code the following text

    update one table

    Office set = (select desktop in table b where b.emp_id = a.emp_id)

    and b.start_date = a.start_date

    and b.office is not null

    )

    where is ([as well as overall query])

    and a.office is null

    In my opinion, who will do the trick.

    HTH - Mark D Powell.

  • Overview and details of the records in the same mixing ratio

    Hello, on the bottom I need to mix the results in the summary table and the records in the table of details in the same report.

    To create the scenario:
    CREATE TABLE ALPHA
    (
    ALPHA_ID     NUMBER,
    ALPHA_NR     NUMBER,
    ALPHA_TOTCT     NUMBER,
    ALPHA_FUND     NUMBER
    
    );
    
    ALTER TABLE ALPHA ADD (
         CONSTRAINT ALPHA_PK PRIMARY KEY (ALPHA_ID));
    ALTER TABLE ALPHA ADD (
         CONSTRAINT ALPHA_NR_UNI UNIQUE (ALPHA_NR));
    
    
    INSERT INTO ALPHA(ALPHA_ID, ALPHA_NR)
    VALUES( 1, 7 );
    INSERT INTO ALPHA(ALPHA_ID, ALPHA_NR)
    VALUES( 2, 11 );
    INSERT INTO ALPHA(ALPHA_ID, ALPHA_NR)
    VALUES( 3, 15 );
    INSERT INTO ALPHA(ALPHA_ID, ALPHA_NR)
    VALUES( 4, 17 );
    
    CREATE TABLE HIST
    (
    HIST_ID     NUMBER,
    HIST_NR NUMBER,
    HIST_ALPHA_NR NUMBER,
    HIST_CT          NUMBER,
    HIST_VAL     NUMBER,
    HIST_DATE     DATE
    
    );
    
    ALTER TABLE HIST ADD (
         CONSTRAINT HIST_PK PRIMARY KEY (HIST_ID));
    ALTER TABLE HIST ADD (
         CONSTRAINT HIST_NR_UNI UNIQUE (HIST_NR));
    ALTER TABLE HIST ADD (
         CONSTRAINT HIST_ALPHA_NR_FK FOREIGN KEY (HIST_ALPHA_NR) REFERENCES ALPHA ( ALPHA_NR ) );
    
    TRUNCATE TABLE HIST;
    
    INSERT INTO HIST( HIST_ID ,HIST_NR ,HIST_ALPHA_NR ,HIST_CT ,HIST_VAL ,HIST_DATE )
    VALUES ( 1 ,1    ,7 ,1 ,10 , TO_DATE('01.02.2009' , 'dd.mm.yyyy' ) );
    INSERT INTO HIST( HIST_ID ,HIST_NR ,HIST_ALPHA_NR ,HIST_CT ,HIST_VAL ,HIST_DATE )
    VALUES ( 2 ,6    ,7 ,1 ,10 , TO_DATE('01.05.2009' , 'dd.mm.yyyy' ) );
    INSERT INTO HIST( HIST_ID ,HIST_NR ,HIST_ALPHA_NR ,HIST_CT ,HIST_VAL ,HIST_DATE )
    VALUES ( 3 ,3    ,7 ,3 ,30 , TO_DATE('01.02.2010' , 'dd.mm.yyyy' ) );
    
    
    INSERT INTO HIST( HIST_ID ,HIST_NR ,HIST_ALPHA_NR ,HIST_CT ,HIST_VAL ,HIST_DATE )
    VALUES ( 4 ,4    ,11 ,1 ,10 , TO_DATE('01.03.2009' , 'dd.mm.yyyy' ) );
    INSERT INTO HIST( HIST_ID ,HIST_NR ,HIST_ALPHA_NR ,HIST_CT ,HIST_VAL ,HIST_DATE )
    VALUES ( 5 ,5    ,11 ,-2 ,-20 , TO_DATE('01.06.2010' , 'dd.mm.yyyy' ) );
    INSERT INTO HIST( HIST_ID ,HIST_NR ,HIST_ALPHA_NR ,HIST_CT ,HIST_VAL ,HIST_DATE )
    VALUES ( 6 ,8    ,11 ,1 ,10 , TO_DATE('01.02.2011' , 'dd.mm.yyyy' ) );
    
    INSERT INTO HIST( HIST_ID ,HIST_NR ,HIST_ALPHA_NR ,HIST_CT ,HIST_VAL ,HIST_DATE )
    VALUES ( 7 ,2    ,15 ,2 ,20 , TO_DATE('01.03.2009' , 'dd.mm.yyyy' ) );
    INSERT INTO HIST( HIST_ID ,HIST_NR ,HIST_ALPHA_NR ,HIST_CT ,HIST_VAL ,HIST_DATE )
    VALUES ( 8 ,7    ,15 ,5 ,50 , TO_DATE('01.06.2010' , 'dd.mm.yyyy' ) );
    INSERT INTO HIST( HIST_ID ,HIST_NR ,HIST_ALPHA_NR ,HIST_CT ,HIST_VAL ,HIST_DATE )
    VALUES ( 9 ,9    ,15 ,-4 ,-40 , TO_DATE('01.02.2011' , 'dd.mm.yyyy' ) );
    
    INSERT INTO HIST( HIST_ID ,HIST_NR ,HIST_ALPHA_NR ,HIST_CT ,HIST_VAL ,HIST_DATE )
    VALUES ( 10 ,10    ,17 ,1 ,10 , TO_DATE('01.03.2011' , 'dd.mm.yyyy' ) );
    To update the summary table, I used a view
    CREATE OR REPLACE VIEW HIST_AGG ( HIST_ALPHA_NR,  TOT_CT  , TOT_VAL )
    AS
    SELECT HIST_ALPHA_NR
    ,SUM ( NVL(HIST_CT, 0 ) ) TOT_CT
    ,SUM( NVL(HIST_VAL, 0) )  TOT_VAL
    
    FROM HIST
    GROUP BY HIST_ALPHA_NR;
    
    
    DECLARE
    
    CURSOR cur
    IS
    SELECT
    HIST_ALPHA_NR
    ,TOT_CT
    ,TOT_VAL
    FROM HIST_AGG
    ;
    
    BEGIN
    FOR rec IN cur
    LOOP
    
         UPDATE ALPHA
         SET ALPHA_TOTCT = rec.TOT_CT
         , ALPHA_FUND  = rec.TOT_VAL
         WHERE ALPHA_NR = rec.HIST_ALPHA_NR;
    
    END LOOP;
    
    END;
    First report should the line overview Alpha tracked table of all the detail records of
    HIST table and for each alpha_nr. At the end of report total overview
    alpha of the table.
    "SUMMARY";"ALPHA_NR";"ALPHA_TOTCT";"ALPHA_FUND";
    ;;;;
    ;7;5;50;
    ;7;1;10;01.02.2009
    ;7;1;10;01.05.2009
    ;7;3;30;
    ;11;0;0;
    ;11;1;10;01.03.2009
    ;11;-2;-20;01.06.2010
    ;11;1;10;01.02.2011
    ;15;3;30;
    ;15;2;20;01.03.2009
    ;15;5;50;01.06.2010
    ;15;-4;-40;01.02.2011
    ;17;1;10;
    ;17;1;10;01.03.2011
    "TOTAL_ALPHA_NR";4;9;90;
    Second report should display the overview by period (year), but the timeline
    for example the year 2009 begins from the year 2010. At the end of each year a summary for
    the current state.
    "YEAR";"ALPHA_NR";"ALPHA_TOTCT";"ALPHA_FUND"
    ;;;
    2009;7;0;0
    ;11;0;0
    ;15;0;0
    ;17;0;0
    "Total 2009";4;0;0
    2010;7;2;20
    ;11;1;10
    ;15;2;20
    ;17;0;0
    "Total 2010";4;5;50
    2011;7;5;50
    ;11;-1;-10
    ;15;7;70
    ;17;0;0
    "Total 2011";4;11;110
    2012;7;5;50
    ;11;0;0
    ;15;3;30
    ;17;1;10
    "Total 2012";4;9;90

    Hello

    wucis wrote:
    I now use this selection

    ...
    FROM       hist        h
    ,       alpha        a
    WHERE       h.hist_alpha_nr (+)     = a.alpha_nr
    AND       a.active          = 'Y'
    AND a.alpha_nr >=  NVL ( NULL  , 1 )
    AND a.alpha_nr <=  NVL ( NULL  , 10000 )
    AND a.alpha_date >= NVL ( TO_DATE( '02.01.2008'  , 'dd.mm.yyyy' ) , '01.01.2000' )
    --AND h.hist_date  >= NVL ( TO_DATE( NULL  , 'dd.mm.yyyy' ) , '01.01.2000' )
    --AND h.hist_date <= NVL ( TO_DATE( NULL  , 'dd.mm.yyyy' ) , '02.02.2222')
    ...
    

    The problem is now, if I limit the query about the h.hist_date, the lines disappear when there is no entry in HIST for this ALPHA_NR,
    in particular the line with alpha_nr = 12 disappears.

    When you use the old notation join, outer join, whenever a column of a table is marked with the + sign, then all the conditions in the WHERE clause that references the same table need a sign +. Otherwise, the effect is identical to an inner join.
    Using the old syntax, you must say something like:

    ...
    FROM       hist        h
    ,       alpha        a
    WHERE       h.hist_alpha_nr (+)     = a.alpha_nr
    AND       a.active          = 'Y'
    AND        a.alpha_nr          >=  1
    AND        a.alpha_nr           <=  10000
    AND        a.alpha_date           >=  TO_DATE ('01.01.2000', 'dd.mm.yyyy')
    AND        h.hist_date (+)     >=  TO_DATE ('01.01.2000', 'dd.mm.yyyy')
    AND       h.hist_date (+)     <=  TO_DATE ('02.02.2222', 'dd.mm.yyyy')
    ...
    

    Notice the + sign in the last 2 lines, after the columns in this table of reference h. I find the ANSI join syntax much more clear in this case.

    How you use NVL makes no sense. NVL (NULL, x) returns x, no matter what x is.
    What you trying to do? Perhaps you meant

    AND        NVL (a.alpha_nr, 1)          >=  1
    
  • comparing string values in the same table

    I have a table with ID (14 digit string values) starting with "A". Ex: A21849B1020792. There may be a different ID with the same substring 'B1020792' in the same table, example: A12349B1020792. If this happens, the ID of the last creation date of must be returned in the result. In other words, comparison is done on the same table. "In the example provided, say A12349B1020792 has the date of 1 January 2015 'and A21849B1020792 has date February 1, 2015", since A21849B1020792 has the most recent date, the result must contain only A21849B1020792.

    ID create_date

    ---                              ------------------

    A21849B1020792 02/01/2015

    A12349 B1020792 01/01/2015

    A12345B1234567 01/03/2015      

    A43567B1234567 01/04/2015      


    Here's the query I used:

    substr (a.id, 7) select sc, max (a.create_date) cd1

    of table a, table b

    where a.id! = b.id

    and substr (a.id, 7) = substr (b.id, 7)

    and a.id like 'A %' and b.id like 'A %' / * (I used a % because I am interested only IDs that begin with A) * /.

    and a.id ('A12349B1020792', 'A21849B1020792','A12345B1234567 ','A43567B1234567')

    Group of substr (a.id, 7);

    Result:

    ---------

    sc                    cd1

    ---                    ------

    B1020792 02/01/2015

    B1234567 04/01/2015

    There is one thing that I'm not able to do with my request, that is, be able to get real IDs list and not list of substrings. If I added a.id column in the select clause and the group by clause, the query includes both by substr (a.id, 7) and a.id and as a result, the query returns four lines as below:

    substr (a.id, 7) select sc, max (a.create_date) cd1, a.id ID

    of table a, table b

    where a.id! = b.id

    and substr (a.id, 7) = substr (b.id, 7)

    and a.id like 'A %' and b.id like 'A %' / * (I used a % because I am interested only IDs that begin with A) * /.

    and a.id ('A12349B1020792', 'A21849B1020792','A12345B1234567 ','A43567B1234567')

    Group by substr (a.id, 7), a.id.

    Result:

    ---------

    sc                    cd1                      ID

    ---                    ------                   ---------

    01/01/2015 A12349B1020792 B1020792

    B1020792 01/02/2015 A21849B1020792

    B1234567 01/03/2015 A12345B1234567

    B1234567 01/04/2015 A43567B1234567


    My goal is to retrieve a list of all the unique identifiers that have the later dates.


    ID:

    ---

    A21849B1020792

    A43567B1234567


    Thanks for your time in advance!

    Hello

    user11951344 wrote:

    I have a table with ID (14 digit string values) starting with "A". Ex: A21849B1020792. There may be a different ID with the same substring "B1020792" in the same table, example: A12349B1020792. If this is the case, the ID of the last creation date must be returned in the result. In other words, comparison is done on the same table. "In the example provided, say A12349B1020792 updated 1 January 2015 ' and A21849B1020792 a date February 1, 2015", as A21849B1020792 has the most recent date, the result should contain only the A21849B1020792.

    ID create_date

    ---                              ------------------

    A21849B1020792 02/01/2015

    A12349B1020792 01/01/2015

    A12345B1234567 03/01/2015

    A43567B1234567 01/04/2015

    Here's the query I used:

    substr (a.id, 7) select sc, max (a.create_date) cd1

    of table a, table b

    where a.id! = b.id

    and substr (a.id, 7) = substr (b.id, 7)

    and a.id like 'A %' and b.id like 'A %' / * (I used a % because I am interested only IDs that begin with A) * /.

    and a.id ('A21849B1020792', 'A12345B1234567', 'A12349B1020792', 'A43567B1234567')

    Group of substr (a.id, 7);

    Result:

    ---------

    sc                    cd1

    ---                    ------

    B1020792 02/01/2015

    B1234567 01/04/2015

    There is one thing that I am not able to do with my request, that is, the ability to retrieve the list of IDs real and not a list of substrings. If I added a.id column in the select clause and the group by clause, the query groups according to the two substr (a.id, 7) and a.id and as a result, the query returns four lines as below:

    substr (a.id, 7) select sc, max (a.create_date) cd1, a.id ID

    of table a, table b

    where a.id! = b.id

    and substr (a.id, 7) = substr (b.id, 7)

    and a.id like 'A %' and b.id like 'A %' / * (I used a % because I am interested only IDs that begin with A) * /.

    and a.id ('A21849B1020792', 'A12345B1234567', 'A12349B1020792', 'A43567B1234567')

    Group by substr (a.id, 7), a.id.

    Result:

    ---------

    sc                    cd1                      ID

    ---                    ------                   ---------

    B1020792 01/01/2015 A12349B1020792

    B1020792 02/01/2015 A21849B1020792

    B1234567 03/01/2015 A12345B1234567

    B1234567 01/04/2015 A43567B1234567

    My goal is to retrieve a list of all the unique identifiers that have the later dates.

    ID:

    ---

    A21849B1020792

    A43567B1234567

    Thanks for your time in advance!

    If it makes sense to treat the first 6 characters of the ID separately from the rest of the id in this problem, maybe it makes sense to store those two parts of the id in two different columns.  Relational databases work best when each column of each row contains 1 single piece of data (at most).  It is so fundamental to the design of table that he called the first normal form.

    Given that the two parts are stored in column 1, so you can something like this Request Top - N:

    WITH got_r_num AS

    (

    SELECT r.id

    r.create_date AS cd1

    , RANK () OVER (PARTITION OF SUBSTR (r.id, 7))

    ORDER BY r.create_date DESC

    ) AS r_num

    FROM table_x g - g for data values

    JOIN table_x r - r for related values

    ON SUBSTR (r.id, 7) = SUBSTR (g.id, 7)

    WHERE g.id IN ('A12349B1020792'

    , "A21849B1020792".

    , "A12345B1234567".

    , "A43567B1234567".

    )

    - AND g.id LIKE 'A %' - if necessary.   The above condition ensures already g.id start with "A".

    AND r.id LIKE 'a % '.

    )

    SELECT id, create_date

    OF got_r_num

    WHERE r_num = 1

    ;

    If you would care to post CREATE TABLE and INSERT instructions for the sample data, and then I could test this.

  • Update of several rows of the same table using trigger

    Hello

    I have the following table

    ---------------------------------------------------------------------------------------------------------

    CREATE TABLE ATT_PERMISSIONS
    (
    DATE OF PRMONTHYR,
    EMPIDNUMBER (10)DEFAULT VALUE 0,
    FROMDATETIMEDATE,
    TODMTFDATETIMEDATE,
    NUMBER OF PERMMINS (3),

    SSLINASTRETCH NUMBER (3).

    PERMATTINELIGIBLENUMBER (1)DEFAULT VALUE 0
    );

    ------------------------------------------------------------------------------------------------------

    I want to update the column PERMATTINELIGIBLE in the same table when each line is inserted.

    I created following trigger for that

    CREATE OR REPLACE TRIGGER SSL_AFTER_UPDATE AFTER UPDATE ON ATT_PERMISSIONS

    FOR EACH LINE

    BEGIN

    Update ATT_PERMISSIONS set PERMATTINELIGIBLE =

    (

    SELECT THE CHECK BOX

    WHEN PERMMINS < = 60

    or

    (

    PERMMINS < = SSLINASTRETCH

    AND

    COUNT (CASE WHEN PERMMINS = 0 THEN NULL OTHERWISE 1 END)

    COURSES (PARTITION BY empid, prmonthyr) < = 1

    )

    THEN 1

    0 OTHERWISE

    END

    FROM ATT_PERMISSIONS where prmonthyr =:new.prmonthyr, empid =:new.empid

    ) where prmonthyr =:new.prmonthyr, empid =:new.empid;

    END;

    ---------------------------------------------------------------------------------------------------

    That is to say.

    When a row is inserted the PERMATTINELIGIBLE of all records for this employee for the month is recalculated.

    There would be only two or three records for an employee for a month.

    PERMMINS is the number of minutes to use as short leave.

    If it is less than 60 is eligible for the bonus to attendance for this employee.

    If this isn't normally the date is not eligible for the attendance for this employee premium.

    but an exception is that if a short leaves of DISP employee allowed a month (IE. ( SSLINASTRETCH ) in a straight line, IE. one day, that day is eligible for the bonus of presence.

    That is to say. Why the number of short leaves in a month is taken. If it's one and done minutes use is lower to SSLINASTRETCH, then the day is eligible for the attendance bonus.

    But when I try to create the trigger I get error, PL/SQL: ORA-00907: missing a right parenthesis.

    Help, please

    I use oracle 10g

    I want to update the column PERMATTINELIGIBLE in the same table, when each row is inserted.

    No - you do NOT want to do in a trigger.

    You cannot query the same table that the trigger is activated on. -C' is a MUTANT and you will get an exception.

    When a row is inserted is recalculated to the PERMATTINELIGIBLE of all the records for that employee for that month.

    There would be only two or three records for an employee for a month.

    PERMMINS is the number of minutes to use as short leave.

    If it is less than 60 is eligible for the bonus to attendance for this employee.

    If is not normally the day is not eligible for the premium of attendance for this employee.

    but an exception is that if a short leaves of DISP employee allowed a month (IE. SSLINASTRETCH) in a straight line, IE. one day, that day is eligible for the bonus of presence.

    That is to say. Why the number of short leaves in a month is taken. If it's one and done minutes use is less than SSLINASTRETCH, then the day is eligible for the bonus of presence.

    But when I try to create the trigger I get error, PL/SQL: ORA-00907: missing a right parenthesis.

    You can not do in a trigger. Even if correct you this error of syntax, you will get the exception that I mentioned above.

    Oracle is a multi-user system. Other users can modify the same table that you use.

    So even if you could try to interview "all the records for this employee" some of them may be locked if other users access them. Also, an insert statement could try to insert two rows for an employee and the trigger could not have seen the other lines still.

    If you want to work with data SETS (all records for an employee), you must write the PL/SQL code that LOCKS all lines updated to prevent others to interfere.

    Then you make your operations but NOT in a trigger. Perform inserts and then use an UPDATE query to set this value.

    Then VALIDATE to unlock the lines.

Maybe you are looking for

  • Broken space on MacBook Air

    I have a MacBook Air, I tried to clean below the space bar. I think I broke it because when I put back it together it is incredibly hard to push and I need to move so he could push. How can I fix? I just need to get a new keyboard?

  • Satellite Pro A10: Error when loading the drivers and other things

    Hello.I just bought a spare A10 to ebay. I already have an A10 and the company. Powering up the new A10, I have a bubble message from microsoft saying that it was unable to load the drivers for the cd burning software, please update the drivers. If I

  • Re: Satellite A300-29n - blue screen appears during installation of XP?

    Hello I'm working on windows vista and no problemsWhen I tried to put in place XP on the machine, after loading windows filesIt was written "the installation program starts windows.everything was finea blue screen appeared (a problem has been detecte

  • Y40 - 70, off when disconnected.

    Hello everyone. I bought a computer from Lenovo y40-70 in early January and so far I really liked it. But just the other day, I started having some strange problems that I am frankly at a loss to solve. It has progressed in several stages, and I'm a

  • spambox gmail

    If it does not show in the upper left corner, where the gmail spam box?