Select query that eliminate duplicates

I am struck at the below scenario. need your help in modify my query based on the below sample data. My objective is to create a EVENT AND EVENT_LOW using the data available from TEM_GT and TXN table.
TEM_GT (global temporary table)
est_id primary key, trans_id, trp_id, amount
1 111 2221 1.5
2 111 3332 2.0
3 112 4443 3.0
TXN table
trans_id, trans_type
111 type1
112 type1
EVENT table
event_id primary key, trans_id, trans_type, flag.
1000 111 type1 N
1001 112 type1 N
EVENT_LOW table
event_low_id primary key, event_id, est_id, amount.
9991 1000 1 1.5
9992 1000 1 2.0
9993 1001 2 3.0
insert into(event_low_id, event_id, est_id, amount)
select event_low_id_s.nextval e.event_id, tg.est_id, tg.amount from
from TEM_GT tg, EVENT e
WHERE
tg.trans_id = e.trans_id
AND e.flag = 'N'
Based on TEM_GT and TXN gt, populating data into EVENT table. Now when I try to populate data in the EVENT_LOW table, the above query returns 5 rows instead of 3 rows. This is due to trp_id in TEM_GT table. I do not want to add trp_id in EVENT table, and want to handle the duplicate elimination in the above select query.
I wrote the below sql. It almost resolve my problem. But sometimes it returns different value for the amount column. I wanted my event_low result as below for the est_id 1.
event_low_id primary key, event_id, est_id, amount.
9991 1000 1 1.5
9992 1000 1 2.0
But sometime it returns as below
event_low_id primary key, event_id, est_id, amount.
9991 1000 1 1.5
9992 1000 1 1.5
or
event_low_id primary key, event_id, est_id, amount.
9991 1000 1 2.0
9992 1000 1 2.0
select *
from (select x.*,
row_number() over (partition by event_id order by event_id) rn
from (seelct e.event_id, tg.est_id, tg.amount
from TEM_GT tg, EVENT e
WHERE
tg.trans_id = e.trans_id
AND e.flag = 'N'
) x
where rn = 1
I am using Oracle 11g. Any help. Thanks in advance.

Hi Suresh,
Please read SQL and PL/SQL FAQ
Whenever you create a thread always post sample data as CREATE TABLE and INSERT statements.
Additionally when you put some code or output please enclose it between two lines starting with {noformat}{noformat}
i.e.:
{noformat}{noformat}
SELECT ...
{noformat}{noformat}
Regarding your problem you said:
Based on TEM_GT and TXN gt, populating data into EVENT table. Now when I try to populate data in the EVENT_LOW table, the above query returns 5 rows instead of 3 rows.
The above query cannot return 5 rows with the data you have posted. You have 3 rows in TEM_GT and 2 rows in EVENT table. The table are joined ontg.trans_id = e.trans_id AND e.flag = 'N'
And the result of the query with your posted data is *3 rows*. So try to be clear.
If your intention is to insert into EVENT_LOW only one row from TEM_GT for the same trans_id then you have to tell us which is the criteria to choose the row between the duplicates (the first by est_id order??).
Also be careful to post valid statements. The statement below is not valid as it is missing the table name after INSERT INTO and there are 2 consecutive FROM keywords:insert into(event_low_id, event_id, est_id, amount)
select event_low_id_s.nextval e.event_id, tg.est_id, tg.amount from
from TEM_GT tg, EVENT e
WHERE
tg.trans_id = e.trans_id
AND e.flag = 'N'
I will make the assumption that you want to select the first row order by est_id during insertion. If this is not what you want, please change the analytic function:INSERT INTO event_low (event_low_id, event_id, est_id, amount)
WITH got_data AS
SELECT e.event_id, tg.est_id, tg.amount
, ROW_NUMBER() OVER(PARTITION BY tg.trans_id ORDER BY tg.est_id) AS rn
FROM tem_gt tg, event e
WHERE tg.trans_id = e.trans_id
AND e.flag = 'N'
SELECT event_low_id_s.NEXTVAL
, event_id, est_id, amount
FROM got_data
WHERE rn = 1;
If this is not what you want please post CREATE TABLE and INSERT statement, and post your expected output (for insertion into EVENT_LOW table) for the data you have posted.
Regards.
Al                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • Query to eliminate duplicates

    I have a table that lists some data. Every day should have one and only one record per organization. I am trying to weed out the duplicates in one query. It doesn't matter which of the duplicates gets deleted, so I could use a (where rownum = 2) clause, but I'm not sure how to get there.
    This query exposes the duplicates:
    select DATE_INDEX, ORG_ID
      from STAFFING_TURNOVER
    group by DATE_INDEX, ORG_ID
    having COUNT(ID) > 1
    order by DATE_INDEX, ORG_IDCan someone help me turn this into a delete query that deletes the second record? Because it is based on a combination of date + organization, the syntax for a subquery-based delete is escaping me.

    Delete from STAFFING_TURNOVER Where RowID in
    (Select Min(RowID) From STAFFING_TURNOVER Group by DATE_INDEX, ORG_ID Having Count(1) > 1)
    Oops, someone posted the same thing.
    If you need to you can execute it more than once if you have more than one. You can also perform an elegant minus query or use a Sub-query to ID the dups. The problem will be performance and depend on how much data you have.
    Edited by: Dev on Dec 1, 2010 3:25 PM

  • How to optimize the select query that is executed in a cursor for loop?

    Hi Friends,
    I have executed the code below and clocked the times for every line of the code using DBMS_PROFILER.
    CREATE OR REPLACE PROCEDURE TEST
    AS
       p_file_id              NUMBER                                   := 151;
       v_shipper_ind          ah_item.shipper_ind%TYPE;
       v_sales_reserve_ind    ah_item.special_sales_reserve_ind%TYPE;
       v_location_indicator   ah_item.exe_location_ind%TYPE;
       CURSOR activity_c
       IS
          SELECT *
            FROM ah_activity_internal
           WHERE status_id = 30
             AND file_id = p_file_id;
    BEGIN
       DBMS_PROFILER.start_profiler ('TEST');
       FOR rec IN activity_c
       LOOP
          SELECT DISTINCT shipper_ind, special_sales_reserve_ind, exe_location_ind
                     INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
                     FROM ah_item --464000 rows in this table
                    WHERE item_id_edw IN (
                             SELECT item_id_edw
                               FROM ah_item_xref --700000 rows in this table
                              WHERE item_code_cust = rec.item_code_cust
                                AND facility_num IN (
                                       SELECT facility_code
                                         FROM ah_chain_div_facility --17 rows in this table
                                        WHERE chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
                                          AND div_id = (SELECT div_id
                                                          FROM ah_div --8 rows in this table
                                                         WHERE division = rec.division)));
       END LOOP;
       DBMS_PROFILER.stop_profiler;
    EXCEPTION
       WHEN NO_DATA_FOUND
       THEN
          NULL;
       WHEN TOO_MANY_ROWS
       THEN
          NULL;
    END TEST;The SELECT query inside the cursor FOR LOOP took 773 seconds.
    I have tried using BULK COLLECT instead of cursor for loop but it did not help.
    When I took out the select query separately and executed with a sample value then it gave the results in a flash of second.
    All the tables have primary key indexes.
    Any ideas what can be done to make this code perform better?
    Thanks,
    Raj.

    As suggested I'd try merging the queries into a single SQL. You could also rewrite your IN clauses as JOINs and see if that helps, e.g.
    SELECT DISTINCT ai.shipper_ind, ai.special_sales_reserve_ind, ai.exe_location_ind
               INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
               FROM ah_item ai, ah_item_xref aix, ah_chain_div_facility acdf, ah_div ad
              WHERE ai.item_id_edw = aix.item_id_edw
                AND aix.item_code_cust = rec.item_code_cust
                AND aix.facility_num = acdf.facility_code
                AND acdf.chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
                AND acdf.div_id = ad.div_id
                AND ad.division = rec.division;ALSO: You are calling ah_internal_data_pkg.get_chain_id (p_file_id) every time. Why not do it outside the loop and just use a variable in the inner query? That will prevent context switching and improve speed.
    Edited by: Dave Hemming on Dec 3, 2008 9:34 AM

  • Problem with select query that includes a date

    I've been fighting with this for about 4 hours - yes, quite literally... I've never been good with date stuff. I have a brain block.
    Anyway, here's the situation:
    I have an Access database that has a time/date field. There are no times, just a date in mm/dd/yyyy format.
    That table is a list of classes held for the past three years. I want to make a query that only shows the classes that have ended after January 1 of this year. I don't want to put 01/01/2010 in the query itself because I want it to still work next year.
    This is the current query:
    <cfquery name="classes" datasource="#DSN#" dbtype="ODBC">
    SELECT classesTitles.ClassTitle, classesTitles.ClassDesc, classCatagories.catagoryName, classes.classStart, classes.classEnd, classes.classNotes, owners.fName, owners.lName, classTime.timeSlot, classes.classID, classes.classLimit
    FROM classCatagories INNER JOIN (((classes INNER JOIN classesTitles ON classes.classTitle = classesTitles.classTitleID) INNER JOIN classTime ON classes.classTime = classTime.timeID) INNER JOIN owners ON classes.classInstructor = owners.ownerID) ON classCatagories.catagoryID = classesTitles.ClassType
    WHERE  classes.classEnd <  01/01/#DatePart("yyyy", now())#
    ORDER BY classes.classStart, classCatagories.catagoryName, classTime.timeSlot, classesTitles.ClassTitle
    </cfquery>
    I don't get any results, but I should get a list of every class that has an end date before January 1 of this year - about 200 records.
    When I swap around the where clause to:
    <cfquery name="classes" datasource="#DSN#" dbtype="ODBC">
    SELECT classesTitles.ClassTitle, classesTitles.ClassDesc, classCatagories.catagoryName, classes.classStart, classes.classEnd, classes.classNotes, owners.fName, owners.lName, classTime.timeSlot, classes.classID, classes.classLimit
    FROM classCatagories INNER JOIN (((classes INNER JOIN classesTitles ON classes.classTitle = classesTitles.classTitleID) INNER JOIN classTime ON classes.classTime = classTime.timeID) INNER JOIN owners ON classes.classInstructor = owners.ownerID) ON classCatagories.catagoryID = classesTitles.ClassType
    WHERE  classes.classEnd > 01/01/#DatePart("yyyy", now())#
    ORDER BY classes.classStart, classCatagories.catagoryName, classTime.timeSlot, classesTitles.ClassTitle
    </cfquery>
    I get EVERY class in the database, and I should only be getting about 50
    The classes are about 8 weeks long, the begin date and end date are in the database as date/time fields, so I need to show everything that ended in 2010, regardless of when it started.
    I'm sure it's something glaringly obvious, but it's escaping me.
    THANKS
    Michelle

    The format of your date field in access is irrelevent to the situation at hand.  Use proper date objects instead of trying to build a suitable string.  For the first of January of the current year, the coldfusion functions createdate(), year(), and now() are your freinds.  Then, in case Adam's post was not clear, use cfqueryparam with the resulting variable.

  • Is there a way to use owa_opt_lock.checksum in Select query that returns multiple records?

    Trying to do something as data would be uploaded and edited in grid. At present I am using Ora_Hash.
    SELECT
            e.ROWID, e.Employee_Id,e.First_Name,e.Last_Name,e.Email,e.Phone_Number,e.Hire_Date,
            e.Job_Id,e.Salary,e.Manager_Id,e.Department_Id,
            owa_opt_lock.checksum('HR','EMPLOYEES', e.rowid) As HashForThisRow
    FROM EMPLOYEES e;
    Thx

    No you can't.
    owa_opt_lock.checksum is a function which is used for optimist locking. It locks the row(probably by using Select FOR Update mechanism) which you select and which you are trying to update. As a result, what you are eventually trying to do is that inside a Select query you are using a function that is locking the rows, which is not allowed. And thus your query will fail with the below mentioned error.
    ORA-14551: cannot perform a DML operation inside a query
    ORA-06512: at "SYS.DBMS_SQL", line 1575
    ORA-06512: at "SYS.OWA_OPT_LOCK", line 172
    14551. 00000 -  "cannot perform a DML operation inside a query "
    *Cause:    DML operation like insert, update, delete or select-for-update
               cannot be performed inside a query or under a PDML slave.
    *Action:   Ensure that the offending DML operation is not performed or
               use an autonomous transaction to perform the DML operation within
               the query or PDML slave.
    Thanks,
    Ishan

  • Tell me select Query that HITs the database Directly  ???

    Hi,
        I have a table, for this table in the Techinical Setttings I selected Buffering allowed, and buffering type is Full Bufferd.Now, I want a Select Query which hits the database directly, without fetching records from the BUFFER.
    Except using SELECT BYPASSING BUFFER query ????
        Regards,
    V.Raghavender.

    hi,
    ·        Any SELECT with a sub query or with joins
    ·        Any set function (COUNT, MIN, MAX, SUM, AVG)
    ·        GROUP BY
    ·        HAVING
    ·        SELECT DISTINCT
    ·        ORDER BY
    Examples:
    SELECT /*@ SAP BYPASSING BUFFER */ * FROM MYTAB
        WHERE KEY1 = ? AND KEY2 = ?
    SELECT * FROM MYTAB WHERE KEY1 = ?
    SELECT * FROM MYTAB
        WHERE KEY1 = ? AND KEY2 = ? OR KEY1 = ?
    SELECT MAX(DATA) FROM MYTAB WHERE KEY1 = ? KEY2 = ?
    SELECT * FROM MYTAB
        WHERE KEY1 = ? AND KEY2 = ? AND DATA =
       (SELECT DATA FROM MYTAB WHERE KEY1 = ? AND KEY2 = ?)
    if helpful pls award points.
    sri

  • How to create a triangle view with a select query?

    I need help to build a select query that will create a triangle view.
    Below is the table I have to query
    *{color:#ff0000}INITIAL TABLE{color}*
    *{color:#008000}AMOUNT | TRANSACTION_DATE | OPEN_DATE | TYPE{color}*
    5 | 30-JAN-09 | 10-JAN-09 | A
    10 | 12-JAN - 09 | 30-NOV-08 | A
    20 | 30 - DEC - 08 | 15-OCT-08 | A
    10 | 30 - DEC - 08 | 8 - OCT - 08 | A
    *{color:#ff0000}THE FINAL TABLE I HAVE TO CREATE:{color}*
    DEV_PERIOD - TO_CHAR(TRUNC(TRANSACTION_DATE,'Q'),'YYYY-Q') AS DEV_PERIOD
    OPEN PERIOD - TO_CHAR(TRUNC(OPEN_DATE,'Q'),'YYYY-Q') AS OPEN_PERIOD
    {color:#008000}*SUM of AMOUNT | DEV_PERIOD | OPEN_PERIOD | TYPE*{color}
    5 | 2009 - 1 | 2009 - 1 | A
    40 | 2009 - 1 | 2008 - 4 | A
    30 | 2008 - 4 | 2008 - 4 | A
    {color:#ff0000}*This is another view of the table (The triangle view)*{color}
    | Dev_Period 2008- 1 | 2008 - 2| 2008 -3 | 2008 - 4 | 2009 -1 |
    Open_Period |
    2008 - 1..................... 0.......... 0............ 0........... 0.......... 0
    2008 - 2 ..................................0............ 0........... 0.......... 0
    2008 - 3................................................. 0........... 0.......... 0
    2008 - 4 ..............................................................30......... 40
    2009 - 1 .............................................................................5
    Any ideas will be appreaciated.
    Thank you!

    I think the first thing you need to do is look up "pivot query" in this newsgroup. And how complicated your query gets to be will depend on your database version (11 natively supports pivot queries). You have a variable number of columns in your result set (depending on how many quarters you have in your data.
    I think once you get the columns sorted out, working out the numbers to put in each column will be relatively easy.
    Jon

  • I need to know the proper syntax for my SELECT query, please.

    Hello All,
    Quick one for you:
    Let's say that I have several columns in a table with names such as subject_1, subject_2, subject_3, etc. The table's name is subject_names.
    The number in each of the three column name examples is also a value passed along a query string, the user can select choices, 1, 2 or 3. That query string's variable is $qs.
    So, what I want is a SELECT query that uses the query string value as follows (KEEP IN MIND, I know this is not the proper syntax):
    "SELECT subject_[$qs]
    FROM subject_names";
    I have tried all sorts of cominations of quotes (single and double), dots, brackets, braces and parenthesis. I just want to know how to include such a variable within this code.
    Any and all help is sincerely appreciated!
    Cheers,
    wordman

    Well, I did give you the syntax though.
    $query = 'SELECT ' . $qs . ' FROM tbl_name';
    I put spaces between the periods this time to make it more clear.
    If you put the actual word 'subject' in there and just want your form to name it's options as the numbers available you could do this:
    $query = 'SELECT subject_' . $qs . ' FROM tbl_name';
    In PHP you can use either single or double quotes around your query string, I always just use single quotes. I see a lot of other use double quotes.
    Double quotes would look like:
    $query = "SELECT subject_' . $qs . ' FROM tbl_name";
    Or when using double quotes you can actually just place the variable right in the string without having to concatenate multiple strings like above.
    Since you mentioned that you are good with passing variables I probably don't have to mention that you need to set the value attribute of your option tags (if you are using a select) to the value you want them to pass.
    Ex:
    <select name="choices">
         <option value="1">1</option>
         <option value="2">2</option>
         <option value="3">3</option>
    </select>
    If you have that part all figured out then you can use the syntax above for your query string.
    Good luck.

  • Select query on QALS table taking around 4 secs to fetch one record

    Hi,
    I have one select query that takes around 4 secs to fetch one record. I would like to know if there are any ways to reduce the time taken for this select.
    SELECT
         b~prueflos
         b~matnr
         b~lagortchrg
         a~vdatum
         a~kzart
         a~zaehler
         a~vcode
         a~vezeiterf
         FROM qals AS b LEFT OUTER JOIN qave AS a ON
         bprueflos = aprueflos
         INTO TABLE t_qals1
         FOR ALL ENTRIES IN t_lgorts
          WHERE  matnr = t_lgorts-matnr
          AND    werk = t_lgorts-werks
          AND    lagortchrg = t_lgorts-lgort
          AND    stat35 = c_x
          AND    art IN (c_01,c_08).
    When I took the SQL trace, here I found other details :
    Column          No.Of Distinct Records
    MANDANT                                      2
    MATNR                                      2.954
    WERK                                          30
    STAT34                                         2
    HERKUNFT                                   5
    Analyze Method                    Sample 114.654 Rows
    Levels of B-Tree                                 2
    Number of leaf blocks                         1.126
    Number of distinct keys                      16.224
    Average leaf blocks per key                1
    Average data blocks per key               3
    Clustering factor                                  61.610
    Also note, This select query is using INDEX RANGE SCAN QALS~D.
    All the suggestions are welcome
    Regards,
    Vijaya

    Hi Rob,
    Its strange but, the table t_lgorts  has only ONE record
    MATNR  =  000000000500003463
    WERK = D133
    LAGORTCHRG   = 0001                                            
    I have also seen that for the above criteria the table QALS has 2266 records that satisfy this condition.
    I am not sure..but if we write the above query as subquery instead of Outer join..will it improve the performance?
    Will check it from my side too..
    Regards,
    Vijaya

  • Regarding performance in select query

    hi to all,
    i wrote select query for fetching duplicate records,like select distinct *.
    so at runtime it fetches all fields in table (FI dbtable).
    but i want to fetch only 8 records,for this i am using
    select distinct
              field1
               field2
    ..... like this ,it wasnt excuted.
    how can i avoid this issue.
    in program not much logic is there,only fetching the data and summation,n display.....
    plz giv me reply asap.
    regards
    satya

    satya wrote:>
    > hi to all,

    >  i wrote select query for fetching duplicate records,like select distinct *.
    > so at runtime it fetches all fields in table (FI dbtable).
    >
    > but i want to fetch only 8 records,for this i am using
    > select distinct
    >           field1
    >            field2
    > ..... like this ,it wasnt excuted.
    >
    > how can i avoid this issue.
    > in program not much logic is there,only fetching the data and summation,n display.....
    >
    > plz giv me reply asap.
    >
    > regards
    > satya
    Hi,
    write like this
    > select field1
    >           field2
    >          .......
    >   from  table
    >   into ( itab-f1,
    >            itab-f2,
    >            ........ )
    <REMOVED BY MODERATOR>
    Edited by: Alvaro Tejada Galindo on Feb 19, 2008 5:14 PM

  • PLSQL Funciton in SELECT query for a region in APEX

    Hello, I am developing a SQL report based on SELECT query that uses a plsql function.
    However the PLSQL Function returns a numeric value and , in addition to that, it also has one out parameter.
    How do I display this out paramete's value on APEX report?
    Thanks,
    R

    From a performance perspective, calling PL/SQL functions from SQL queries is expensive because you context switch between SQL and PL/SQL. That's ok for say 20-30 rows, but as you return more rows it gets more and more expensive. If possible write it all in SQL.
    Tyler Muth
    http://tylermuth.wordpress.com
    "Applied Oracle Security: Developing Secure Database and Middleware Environments": http://sn.im/aos.book

  • Oracle "IO Error" during SELECT query under heavy load

    We're experiencing a strange connection break during SELECT queries under heavy load.
    Platform Details: Solaris, Oracle 11G, JDK 1.6, 
    Application: Spring + Hibernate (C3p0 connection pooling)
    Exact error messages from a lengthy stack trace are mentioned below:
        2013/06/05 18:49:02 | Caused by: org.springframework.dao.DataAccessResourceFailureException: Hibernate operation: could not execute query; SQL [SQL Ommitted]; IO Error: No such file or directory;      nested exception is java.sql.SQLException: IO Error: No such file or directory 
        2013/06/05 18:49:02 | Caused by: java.sql.SQLException: IO Error: No such file or directory
        2013/06/05 18:49:02 |    at oracle.jdbc.driver.T4CPreparedStatement.fetch(T4CPreparedStatement.java:1091)
        2013/06/05 18:49:02 |    at oracle.jdbc.driver.OracleResultSetImpl.close_or_fetch_from_next(OracleResultSetImpl.java:369)
        2013/06/05 18:49:02 |    at oracle.jdbc.driver.OracleResultSetImpl.next(OracleResultSetImpl.java:273)
        2013/06/05 18:49:02 |    at com.mchange.v2.c3p0.impl.NewProxyResultSet.next(NewProxyResultSet.java:2706)
        2013/06/05 18:49:02 |    at org.hibernate.loader.Loader.doQuery(Loader.java:697)
        2013/06/05 18:49:02 | Caused by: java.net.SocketException: No such file or directory
        2013/06/05 18:49:02 |    at java.net.SocketInputStream.socketRead0(Native Method)
        2013/06/05 18:49:02 |    at java.net.SocketInputStream.read(SocketInputStream.java:129)
        2013/06/05 18:49:02 |    at oracle.net.ns.Packet.receive(Packet.java:282)
    We've started looking at TCP connection settings (Max. TCP connections allowed, Max File descriptors allowed for socket connections at system level). Anything we're missing?
    Why "IO Error: No such file or directory"? Any clue?

    user2951561 wrote:
    That's a better answer indeed.
    I can refine my question if it does not provide you enough information.
    The stack trace i displayed here states that oracle jdbc driver has found the connection to be closed, interrupted etc.
    Application behaves perfectly under normal load but blows up as soon as we reach 3000 concurrent sessions. No firewall is breaking connections, the select query that we observe this behavior for is part of a larger workflow that write data, update some, delete some as well in different tables. Then we see above stack trace for the select query.
    I am trying to explore possible options to investigate. One i mentioned is related to Solaris file descriptors. Could it be database it self?
    Any possible course of action for investigation? Help is much appreciated.
    Oracle errors get reported with error code & message; like ORA-01555 Snapshot Too Old; which is not present in your post.
    You indicated that Connection Pooling is used.
    Is there some (artificial) limit within the application that falls off the cliff at 3000 sessions?
    Oracle does not know or care about the "flavor" of client connection. It treats jdbc the same as OCI or ODBC connections.
    Is OS limited to fixed number of open file handles?

  • Select query for rows where condition 1

    Say I have a table, tb1, that has the following entries:
    FName LName
    Code
    John Doe
    xxx
    Jane Doe
    xxx
    Steve Harper
    x
    Barrak Obama
    x
    George Bush
    xxxx
    Bill Clinton
    xx
    I'd like to write a select query that only lists the rows where the count for Code is > 1, i.e not display the last two rows from the above entry. How would I go about writing that select query.
    Thanks.

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    >> Say I have a table, tb1, that has the following entries: <<
    Are you this rude or really ignorant and too lazy to read the Netiquette at the start to this forum? Why do you think you do not need a key? No DDL? No constraints? And , why, why do you think that “tb1” is a precise, ISO-11179 conforming table name? 
    Let's make this a table of rude posters rated on a 4-star scale. 
    CREATE TABLE Rude_Posters
    (first_name VARCHAR(15) NOT NULL, 
     last_name VARCHAR(15) NOT NULL, 
     PRIMARY KEY (first_name, last_name), 
     rudeness_code VARCHAR (4) NOT NULL
       CHECK (rudeness_code IN ('x', 'xx', 'xxx', 'xxxx'));
    INSERT INTO Rude_Posters
    VALUES
    ('John', 'Doe', 'xxx'), 
    ('Jane', 'Doe', 'xxx'), 
    ('Steve', 'Harper', 'x'), 
    ('Barrack', 'Obama', 'x'), 
    ('George', 'Bush', 'xxxx'), 
    ('Bill', 'Clinton', 'xx');
    >> I'd like to write a SELECT query that only lists the rows where the count for rudeness_code is > 1, i.e not display the last two rows from the above entry. << 
    The rudeness scale is based on stars, so to ask for an integer value is like saying “on a scale from 1 to 10, what is the color of your favorite letter of the alphabet?”
    Next, the number of stars and your narrative do not match. Did you want to say WHERE rudeness_code IN ('xx' 'xxx', 'xxxx')? 
    Please stop programming SQL until you have gotten more education. At this point, you do not know enough to ask a question. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Query help to eliminate duplicate inserts

    Hi
    I am inserting records using Insert and select statements. I am having composite primary key on client_id,begin_Dt,end_Dt and service_cd_desc on my target table.
    In order to eliminate duplicate composite key being inserted into the target table I am using NOT IN clause but some how I am error as
    ORA-00001: unique constraint violated (<schema>.<constraint>)
    query is as below:
    insert into stage_2_authorized_service
    (CLIENT_ID
    ,BEGIN_DT
    ,END_DT
    ,DHS_SERVICE_CD
    ,SERVICE_CD_DESC
    ,DHS_SERVICE_GROUP_CD
    ,SERVICE_GROUP_DESC
    ,AUTHORIZED_DOLLARS
    ,AUTHORIZED_UNITS
    ,DHS_AUTHORIZED_UNITS_TYPE_CD
    ,AUTHORIZED_UNITS_TYPE_DESC
    ,CONTRACT_NUMBER
    ,SERVICE_CD
    ,SERVICE_GROUP_CD
    SELECT DISTINCT
    stage_1.CLIENT_ID,
    stage_1.BEGIN_DT,
    stage_1.END_DT,
    stage_1.service_cd as dhs_service_cd,
    dim.service_cd_desc as service_cd_desc,
    stage_1.SERVICE_GROUP_CD as dhs_service_group_cd,
    decode(stage_1.SERVICE_GROUP_cd, '1','NURSING FACILITY','2', 'CLASS','3','CBA','4','STATE OPERATED ICF/MR CAMPUS','5','STATE OPERATED ICF/MR COMMUNITY','6','NON-STATE-OPERATED ICF/MR','7','Community Care','8','Hospice','9','LTC SUPPORT SERVICES (PROVIDER ENROLLMENT)','10','SWING BEDS (WAS PART OF NURSING FACILITY)','11','PACE','12','HCS','13','HCS-O','14','MRLA (MHMR NEW WAIVER)','15','TEXAS HOME LIVING (TxHmL)','16','Deaf Blind Waiver','17','Consolidated Waiver','18','Medically Dependent Children Program (MDCP)','19','STAR+PLUS') as service_group_desc,
    stage_1.AUTHORIZED_DOLLARS,
    stage_1.AUTHORIZED_UNITS,
    stage_1.UNIT_TYPE as DHS_AUTHORIZED_UNITS_TYPE_CD,
    decode(stage_1.UNIT_TYPE,'1','WEEK','2','MONTH','4','PER AUTHORIZATION','5','DAILY') as AUTHORIZED_UNITS_TYPE_DESC ,
    CONTRACT_NUMBER,
    stage_1.service_cd,
    stage_1.service_group_cd
    FROM
    STAGE_1_MG_SERVICE_REQUEST stage_1, stage_3_servcd_servgrp_dim dim
    where
    (stage_1.client_id,stage_1.begin_dt,stage_1.end_dt,dim.service_cd_desc) not in (select distinct stage_1.client_id,stage_1.begin_dt,stage_1.end_dt,dim.service_cd_desc
    from stage_1_mg_service_request stage_1, stage_3_servcd_servgrp_dim dim
    where stage_1.service_cd = dim.service_cd and
    stage_1.service_group_cd = dim.service_group_cd and
    stage_1.service_group_cd in ('2','3','16','17','18')
    Can some one tell me whats wrong with above query
    Any help is appreciated...!
    Thanks
    J

    Yes my target table doesn't have data init at all.Well that is not how you use not in to avoid unique constraint violations
    You need to select only the values that will not violate the constraint something like this untested example.
    select
        client_id,
        begin_dt,
        end_dt,
        service_cd_desc,
        dhs_service_cd,
        dhs_service_group_cd,
        service_group_desc,
        authorized_dollars,
        authorized_units,
        dhs_authorized_units_type_cd,
        authorized_units_type_desc,
        contract_number,
        service_cd,
        service_group_cd
    from
        SELECT    
        count(*) over (partition by
    stage_1.CLIENT_ID,
    stage_1.BEGIN_DT,
    stage_1.END_DT,
    dim.service_cd_desc) the_count,     
        stage_1.CLIENT_ID,
        stage_1.BEGIN_DT,
        stage_1.END_DT,
        stage_1.service_cd as dhs_service_cd,
        dim.service_cd_desc as service_cd_desc,
        stage_1.SERVICE_GROUP_CD as dhs_service_group_cd,
        decode(stage_1.SERVICE_GROUP_cd, '1','NURSING FACILITY','2', 'CLASS','3','CBA',
            '4','STATE OPERATED ICF/MR CAMPUS','5','STATE OPERATED ICF/MR COMMUNITY',
            '6','NON-STATE-OPERATED ICF/MR','7','Community Care','8','Hospice',
            '9','LTC SUPPORT SERVICES (PROVIDER ENROLLMENT)',
            '10','SWING BEDS (WAS PART OF NURSING FACILITY)','11','PACE','12','HCS',
            '13','HCS-O','14','MRLA (MHMR NEW WAIVER)','15','TEXAS HOME LIVING (TxHmL)',
            '16','Deaf Blind Waiver','17','Consolidated Waiver',
            '18','Medically Dependent Children Program (MDCP)','19','STAR+PLUS') as service_group_desc,
        stage_1.AUTHORIZED_DOLLARS,
        stage_1.AUTHORIZED_UNITS,
        stage_1.UNIT_TYPE as DHS_AUTHORIZED_UNITS_TYPE_CD,
        decode(stage_1.UNIT_TYPE,'1','WEEK','2','MONTH',
            '4','PER AUTHORIZATION','5','DAILY') as AUTHORIZED_UNITS_TYPE_DESC ,
        CONTRACT_NUMBER,
        stage_1.service_cd,
        stage_1.service_group_cd
        FROM
        STAGE_1_MG_SERVICE_REQUEST stage_1, stage_3_servcd_servgrp_dim dim
        where
        (stage_1.client_id,stage_1.begin_dt,stage_1.end_dt,dim.service_cd_desc) not in
        (select distinct stage_1.client_id,stage_1.begin_dt,stage_1.end_dt,dim.service_cd_desc
        from stage_1_mg_service_request stage_1, stage_3_servcd_servgrp_dim dim
        where stage_1.service_cd = dim.service_cd and
        stage_1.service_group_cd = dim.service_group_cd and
        stage_1.service_group_cd in ('2','3','16','17','18'))
    where the_count = 1;Link to a working example here
    Re: insert via insert into ....(select * from)....validtion of duplicate re

  • Select Query failing on a  table that has per sec heavy insertions.

    Hi
    Problem statement
    1- We are using 11g as an database.
    2- We have a table that is partitioned on the date as range partition.
    3- The insertion of data is very high.i.e. several hundreds records per sec. in the current partitioned.
    4- The data is continuously going in the current partitioned as and when buffer is full or per sec timer expires.
    5-- We have to make also select query on the same table and on the current partitioned say for the latest 500 records.
    6- Effecient indexes are also created on the table.
    Solutions Tried.
    1- After analyzing by tkprof it is observed that select and execute is working fine but fetch is taking too much time to show the out put. Say it takes 1 hour.
    2- Using the 11g sql advisior and SPM several baseline is created but the success rate of them is observed also too low.
    please suggest any solution to this issue
    1- i.e. Redisgn of table.
    2- Any better way to quey to fix the fetch issue.
    3- Any oracle seetings or parameter changes to fix the fetch issue.
    Thanks in advance.
    Regards
    Vishal Sharma

    I am uploading the latest stats please let me know how can improve as this is taking 25 minutes
    ####TKPROF output#########
    SQL ID : 2j5w6bv437cak
    select almevttbl.AlmEvtId, almevttbl.AlmType, almevttbl.ComponentId,
      almevttbl.TimeStamp, almevttbl.Severity, almevttbl.State,
      almevttbl.Category, almevttbl.CauseCode, almevttbl.UnitType,
      almevttbl.UnitId, almevttbl.UnitName, almevttbl.ServerName,
      almevttbl.StrParam, almevttbl.ExtraStrParam, almevttbl.ExtraStrParam2,
      almevttbl.ExtraStrParam3, almevttbl.ParentCustId, almevttbl.ExtraParam1,
      almevttbl.ExtraParam2, almevttbl.ExtraParam3,almevttbl.ExtraParam4,
      almevttbl.ExtraParam5, almevttbl.SRCIPADDRFAMILY,almevttbl.SrcIPAddress11,
      almevttbl.SrcIPAddress12,almevttbl.SrcIPAddress13,almevttbl.SrcIPAddress14,
      almevttbl.DESTIPADDRFAMILY,almevttbl.DestIPAddress11,
      almevttbl.DestIPAddress12,almevttbl.DestIPAddress13,
      almevttbl.DestIPAddress14,  almevttbl.DestPort, almevttbl.SrcPort,
      almevttbl.SessionDir, almevttbl.CustomerId, almevttbl.ProfileId,
      almevttbl.ParentProfileId, almevttbl.CustomerName, almevttbl.AttkDir,
      almevttbl.SubCategory, almevttbl.RiskCategory, almevttbl.AssetValue,
      almevttbl.IPSAction, almevttbl.l4Protocol,almevttbl.ExtraStrParam4 ,
      almevttbl.ExtraStrParam5,almevttbl.username,almevttbl.ExtraStrParam6,
      IpAddrFamily1,IPAddrValue11,IPAddrValue12,IPAddrValue13,IPAddrValue14,
      IpAddrFamily2,IPAddrValue21,IPAddrValue22,IPAddrValue23,IPAddrValue24
    FROM
           AlmEvtTbl PARTITION(ALMEVTTBLP20100323) WHERE AlmEvtId IN ( SELECT  * FROM
      ( SELECT /*+ FIRST_ROWS(1000) INDEX (AlmEvtTbl AlmEvtTbl_Index) */AlmEvtId
      FROM AlmEvtTbl PARTITION(ALMEVTTBLP20100323) where       ((AlmEvtTbl.Customerid
      = 0 or AlmEvtTbl.ParentCustId = 0))  ORDER BY AlmEvtTbl.TIMESTAMP DESC) 
      WHERE ROWNUM  <  602) order by timestamp desc
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.10       0.17          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch       42   1348.25    1521.24       1956   39029545          0         601
    total       44   1348.35    1521.41       1956   39029545          0         601
    Misses in library cache during parse: 1
    Optimizer mode: FIRST_ROWS
    Parsing user id: 82 
    Rows     Row Source Operation
        601  PARTITION RANGE SINGLE PARTITION: 24 24 (cr=39029545 pr=1956 pw=1956 time=11043 us cost=0 size=7426 card=1)
        601   TABLE ACCESS BY LOCAL INDEX ROWID ALMEVTTBL PARTITION: 24 24 (cr=39029545 pr=1956 pw=1956 time=11030 us cost=0 size=7426 card=1)
        601    INDEX FULL SCAN ALMEVTTBL_INDEX PARTITION: 24 24 (cr=39029377 pr=1956 pw=1956 time=11183 us cost=0 size=0 card=1)(object id 72557)
        601     FILTER  (cr=39027139 pr=0 pw=0 time=0 us)
    169965204      COUNT STOPKEY (cr=39027139 pr=0 pw=0 time=24859073 us)
    169965204       VIEW  (cr=39027139 pr=0 pw=0 time=17070717 us cost=0 size=13 card=1)
    169965204        PARTITION RANGE SINGLE PARTITION: 24 24 (cr=39027139 pr=0 pw=0 time=13527031 us cost=0 size=48 card=1)
    169965204         TABLE ACCESS BY LOCAL INDEX ROWID ALMEVTTBL PARTITION: 24 24 (cr=39027139 pr=0 pw=0 time=10299895 us cost=0 size=48 card=1)
    169965204          INDEX FULL SCAN ALMEVTTBL_INDEX PARTITION: 24 24 (cr=1131414 pr=0 pw=0 time=3222624 us cost=0 size=0 card=1)(object id 72557)
    Elapsed times include waiting on following events:
      Event waited on                             Times   Max. Wait  Total Waited
      ----------------------------------------   Waited  ----------  ------------
      SQL*Net message to client                      42        0.00          0.00
      SQL*Net message from client                    42       11.54        133.54
      db file sequential read                      1956        0.20         28.00
      latch free                                     21        0.00          0.01
      latch: cache buffers chains                     9        0.01          0.02
    SQL ID : 0ushr863b7z39
    SELECT /* OPT_DYN_SAMP */ /*+ ALL_ROWS IGNORE_WHERE_CLAUSE
      NO_PARALLEL(SAMPLESUB) opt_param('parallel_execution_enabled', 'false')
      NO_PARALLEL_INDEX(SAMPLESUB) NO_SQL_TUNE */ NVL(SUM(C1),0), NVL(SUM(C2),0)
    FROM
    (SELECT /*+ IGNORE_WHERE_CLAUSE NO_PARALLEL("PLAN_TABLE") FULL("PLAN_TABLE")
      NO_PARALLEL_INDEX("PLAN_TABLE") */ 1 AS C1, CASE WHEN
      "PLAN_TABLE"."STATEMENT_ID"=:B1 THEN 1 ELSE 0 END AS C2 FROM
      "SYS"."PLAN_TABLE$" "PLAN_TABLE") SAMPLESUB
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.00       0.00          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch        1      0.00       0.01          1          3          0           1
    total        3      0.00       0.01          1          3          0           1
    Misses in library cache during parse: 1
    Misses in library cache during execute: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 82     (recursive depth: 1)
    Rows     Row Source Operation
          1  SORT AGGREGATE (cr=3 pr=1 pw=1 time=0 us)
          0   TABLE ACCESS FULL PLAN_TABLE$ (cr=3 pr=1 pw=1 time=0 us cost=29 size=138856 card=8168)
    Elapsed times include waiting on following events:
      Event waited on                             Times   Max. Wait  Total Waited
      ----------------------------------------   Waited  ----------  ------------
      db file sequential read                         1        0.01          0.01
    SQL ID : bjkdb51at8dnb
    EXPLAIN PLAN SET STATEMENT_ID='PLUS30350011' FOR select almevttbl.AlmEvtId,
      almevttbl.AlmType, almevttbl.ComponentId, almevttbl.TimeStamp,
      almevttbl.Severity, almevttbl.State, almevttbl.Category,
      almevttbl.CauseCode, almevttbl.UnitType, almevttbl.UnitId,
      almevttbl.UnitName, almevttbl.ServerName, almevttbl.StrParam,
      almevttbl.ExtraStrParam, almevttbl.ExtraStrParam2, almevttbl.ExtraStrParam3,
       almevttbl.ParentCustId, almevttbl.ExtraParam1, almevttbl.ExtraParam2,
      almevttbl.ExtraParam3,almevttbl.ExtraParam4,almevttbl.ExtraParam5,
      almevttbl.SRCIPADDRFAMILY,almevttbl.SrcIPAddress11,almevttbl.SrcIPAddress12,
      almevttbl.SrcIPAddress13,almevttbl.SrcIPAddress14,
      almevttbl.DESTIPADDRFAMILY,almevttbl.DestIPAddress11,
      almevttbl.DestIPAddress12,almevttbl.DestIPAddress13,
      almevttbl.DestIPAddress14,  almevttbl.DestPort, almevttbl.SrcPort,
      almevttbl.SessionDir, almevttbl.CustomerId, almevttbl.ProfileId,
      almevttbl.ParentProfileId, almevttbl.CustomerName, almevttbl.AttkDir,
      almevttbl.SubCategory, almevttbl.RiskCategory, almevttbl.AssetValue,
      almevttbl.IPSAction, almevttbl.l4Protocol,almevttbl.ExtraStrParam4 ,
      almevttbl.ExtraStrParam5,almevttbl.username,almevttbl.ExtraStrParam6,
      IpAddrFamily1,IPAddrValue11,IPAddrValue12,IPAddrValue13,IPAddrValue14,
      IpAddrFamily2,IPAddrValue21,IPAddrValue22,IPAddrValue23,IPAddrValue24 FROM 
           AlmEvtTbl PARTITION(ALMEVTTBLP20100323) WHERE AlmEvtId IN ( SELECT  * FROM
      ( SELECT /*+ FIRST_ROWS(1000) INDEX (AlmEvtTbl AlmEvtTbl_Index) */AlmEvtId
      FROM AlmEvtTbl PARTITION(ALMEVTTBLP20100323) where       ((AlmEvtTbl.Customerid
      = 0 or AlmEvtTbl.ParentCustId = 0))  ORDER BY AlmEvtTbl.TIMESTAMP DESC) 
      WHERE ROWNUM  <  602) order by timestamp desc
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.28       0.26          0          0          0           0
    Execute      1      0.01       0.00          0          0          0           0
    Fetch        0      0.00       0.00          0          0          0           0
    total        2      0.29       0.27          0          0          0           0
    Misses in library cache during parse: 1
    Optimizer mode: FIRST_ROWS
    Parsing user id: 82 
    Elapsed times include waiting on following events:
      Event waited on                             Times   Max. Wait  Total Waited
      ----------------------------------------   Waited  ----------  ------------
      SQL*Net message to client                       1        0.00          0.00
      SQL*Net message from client                     1        0.00          0.00
    OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
    call     count       cpu    elapsed       disk      query    current        rows
    Parse       13      0.71       0.96          3         10          0           0
    Execute     14      0.20       0.29          4        304         26          21
    Fetch       92   2402.17    2714.85       3819   70033708          0        1255
    total      119   2403.09    2716.10       3826   70034022         26        1276
    Misses in library cache during parse: 10
    Misses in library cache during execute: 6
    Elapsed times include waiting on following events:
      Event waited on                             Times   Max. Wait  Total Waited
      ----------------------------------------   Waited  ----------  ------------
      SQL*Net message to client                      49        0.00          0.00
      SQL*Net message from client                    48       29.88        163.43
      db file sequential read                      1966        0.20         28.10
      latch free                                     21        0.00          0.01
      latch: cache buffers chains                     9        0.01          0.02
      latch: session allocation                       1        0.00          0.00
    OVERALL TOTALS FOR ALL RECURSIVE STATEMENTS
    call     count       cpu    elapsed       disk      query    current        rows
    Parse      940      0.51       0.73          1          2         38           0
    Execute   3263      1.93       2.62          7       1998         43          23
    Fetch     6049      1.32       4.41        214      12858         36       13724
    total    10252      3.78       7.77        222      14858        117       13747
    Misses in library cache during parse: 172
    Misses in library cache during execute: 168
    Elapsed times include waiting on following events:
      Event waited on                             Times   Max. Wait  Total Waited
      ----------------------------------------   Waited  ----------  ------------
      db file sequential read                        88        0.04          0.62
      latch: shared pool                              8        0.00          0.00
      latch: row cache objects                        2        0.00          0.00
      latch free                                      1        0.00          0.00
      latch: session allocation                       1        0.00          0.00
       34  user  SQL statements in session.
    3125  internal SQL statements in session.
    3159  SQL statements in session.
    Trace file: ora11g_ora_2064.trc
    Trace file compatibility: 11.01.00
    Sort options: default
           6  sessions in tracefile.
          98  user  SQL statements in trace file.
        9111  internal SQL statements in trace file.
        3159  SQL statements in trace file.
          89  unique SQL statements in trace file.
       30341  lines in trace file.
        6810  elapsed seconds in trace file.
    ###################################### AutoTrace Output#################  
    Statistics
           3901  recursive calls
              0  db block gets
       39030275  consistent gets
           1970  physical reads
            140  redo size
         148739  bytes sent via SQL*Net to client
            860  bytes received via SQL*Net from client
             42  SQL*Net roundtrips to/from client
             73  sorts (memory)
              0  sorts (disk)
            601  rows processed

Maybe you are looking for

  • How to transfer the tables from one file group to another file group in SQL 2008.?

    Hello all, I have few issues regarding the transfer of the tables from one file group to another file group  in SQL 2008 and also How can we  backup and restore the particular database based on file group level. Let’s say I have a tables stored withi

  • Problems with Port Forwarding for RDP in WebVPN

    Hi, I'm hoping somebody can help me solve this problem that's been bugging for weeks. We recently implemented a double-layer firewall architecture. Before that, our users can access RDP via port forwarding on WebVPN or the Cisco VPN client without an

  • Help Needed on Using IPC in ISA 4.0

    Hi All I am working on ISA 4.0 and want to change the pricing shown on Product Detail page. I know only a bit about IPC at this moment. Our CRM is configured to look up to R/3 that is what my ABAP Team lead told me. In ISA it is Calling PriceCalculat

  • Regarding MM

    Hi Experts, My question is if  i want to create a new material via copy from another material through MM01, and i need that only those views of material get activated which were in material from which iam copying and i am not aware about the views of

  • Infoset/query : how to fix a selection field value?

    I am writing queries with SQ01 and designing Infosets with SQ02. I have to restrict the results of a query to a specific plant. This can be done by adding the plant field in the selection screen of the query and by asking the users to fill always the