Need a query for duplicate records deletion

here is one scenario...
23130 ----> 'A'
23130 ----> 'X'
23130 ----> 'c'
These are duplicate records.. when we remove duplicates, the record must get 'c', if it contains A,C,X. If it contains A and X, then the record must get 'X'. That means the priority goes like this C-->X-->A. for this i need query.. this is one scenario. It would be great if u reply me asap.

Hello
It's great that you gave examples of your data, but it is quite helpful to supply create table and insert statements too along with a clear example of expected results. Anyway, I think this does what you are looking for.
CREATE TABLE dt_dup (ID NUMBER, flag VARCHAR2(1))
INSERT INTO dt_dup VALUES(23130, 'A');
insert into dt_dup values(23130, 'X');
insert into dt_dup values(23130, 'C');
INSERT INTO dt_dup VALUES(23131, 'A');
INSERT INTO dt_dup VALUES(23131, 'X');
DELETE
FROM
  dt_dup
WHERE
  ROWID IN (  SELECT
                rid
              FROM
                (   SELECT
                      rowid rid,
                      ROW_NUMBER() OVER (PARTITION BY ID ORDER BY CASE
                                                                    WHEN flag = 'A' THEN
                                                                      3
                                                                    WHEN flag = 'X' THEN
                                                                      2
                                                                    WHEN flag = 'C' THEN
                                                                      1
                                                                  END
                                        ) rn
                    FROM
                      dt_dup
              WHERE
                rn > 1
select * from dt_dup;HTH
David
Edited by: Bravid on Jun 30, 2011 8:12 AM

Similar Messages

  • How to tune the query for duplicate records while joining the two tables

    hi,i am executing the query which has retrieving multiple tables,in which one of them has duplicate record,how to get single record

    Not enough info...subject says "tune" the query, message says "write" the query...and where is actual query that you had tried ?

  • Check for duplicate record in SQL database before doing INSERT

    Hey guys,
           This is part powershell app doing a SQL insert. BUt my question really relates to the SQL insert. I need to do a check of the database PRIOR to doing the insert to check for duplicate records and if it exists then that record needs
    to be overwritten. I'm not sure how to accomplish this task. My back end is a SQL 2000 Server. I'm piping the data into my insert statement from a powershell FileSystemWatcher app. In my scenario here if the file dumped into a directory starts with I it gets
    written to a SQL database otherwise it gets written to an Access Table. I know silly, but thats the environment im in. haha.
    Any help is appreciated.
    Thanks in Advance
    Rich T.
    #### DEFINE WATCH FOLDERS AND DEFAULT FILE EXTENSION TO WATCH FOR ####
                $cofa_folder = '\\cpsfs001\Data_pvs\TestCofA'
                $bulk_folder = '\\cpsfs001\PVS\Subsidiary\Nolwood\McWood\POD'
                $filter = '*.tif'
                $cofa = New-Object IO.FileSystemWatcher $cofa_folder, $filter -Property @{ IncludeSubdirectories = $false; EnableRaisingEvents= $true; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' }
                $bulk = New-Object IO.FileSystemWatcher $bulk_folder, $filter -Property @{ IncludeSubdirectories = $false; EnableRaisingEvents= $true; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' }
    #### CERTIFICATE OF ANALYSIS AND PACKAGE SHIPPER PROCESSING ####
                Register-ObjectEvent $cofa Created -SourceIdentifier COFA/PACKAGE -Action {
           $name = $Event.SourceEventArgs.Name
           $changeType = $Event.SourceEventArgs.ChangeType
           $timeStamp = $Event.TimeGenerated
    #### CERTIFICATE OF ANALYSIS PROCESS BEGINS ####
                $test=$name.StartsWith("I")
         if ($test -eq $true) {
                $pos = $name.IndexOf(".")
           $left=$name.substring(0,$pos)
           $pos = $left.IndexOf("L")
           $tempItem=$left.substring(0,$pos)
           $lot = $left.Substring($pos + 1)
           $item=$tempItem.Substring(1)
                Write-Host "in_item_key $item in_lot_key $lot imgfilename $name in_cofa_crtdt $timestamp"  -fore green
                Out-File -FilePath c:\OutputLogs\CofA.csv -Append -InputObject "in_item_key $item in_lot_key $lot imgfilename $name in_cofa_crtdt $timestamp"
                start-sleep -s 5
                $conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=PVSNTDB33; Initial Catalog=adagecopy_daily; Integrated Security=TRUE")
                $conn.Open()
                $insert_stmt = "INSERT INTO in_cofa_pvs (in_item_key, in_lot_key, imgfileName, in_cofa_crtdt) VALUES ('$item','$lot','$name','$timestamp')"
                $cmd = $conn.CreateCommand()
                $cmd.CommandText = $insert_stmt
                $cmd.ExecuteNonQuery()
                $conn.Close()
    #### PACKAGE SHIPPER PROCESS BEGINS ####
              elseif ($test -eq $false) {
                $pos = $name.IndexOf(".")
           $left=$name.substring(0,$pos)
           $pos = $left.IndexOf("O")
           $tempItem=$left.substring(0,$pos)
           $order = $left.Substring($pos + 1)
           $shipid=$tempItem.Substring(1)
                Write-Host "so_hdr_key $order so_ship_key $shipid imgfilename $name in_cofa_crtdt $timestamp"  -fore green
                Out-File -FilePath c:\OutputLogs\PackageShipper.csv -Append -InputObject "so_hdr_key $order so_ship_key $shipid imgfilename $name in_cofa_crtdt $timestamp"
    Rich Thompson

    Hi
    Since SQL Server 2000 has been out of support, I recommend you to upgrade the SQL Server 2000 to a higher version, such as SQL Server 2005 or SQL Server 2008.
    According to your description, you can try the following methods to check duplicate record in SQL Server.
    1. You can use
    RAISERROR to check the duplicate record, if exists then RAISERROR unless insert accordingly, code block is given below:
    IF EXISTS (SELECT 1 FROM TableName AS t
    WHERE t.Column1 = @ Column1
    AND t.Column2 = @ Column2)
    BEGIN
    RAISERROR(‘Duplicate records’,18,1)
    END
    ELSE
    BEGIN
    INSERT INTO TableName (Column1, Column2, Column3)
    SELECT @ Column1, @ Column2, @ Column3
    END
    2. Also you can create UNIQUE INDEX or UNIQUE CONSTRAINT on the column of a table, when you try to INSERT a value that conflicts with the INDEX/CONSTRAINT, an exception will be thrown. 
    Add the unique index:
    CREATE UNIQUE INDEX Unique_Index_name ON TableName(ColumnName)
    Add the unique constraint:
    ALTER TABLE TableName
    ADD CONSTRAINT Unique_Contraint_Name
    UNIQUE (ColumnName)
    Thanks
    Lydia Zhang

  • Need a query for monthly Report

    Hello All,
    I need a query for monthly report,
    comp_code
    emp_id
    dept_id
    work_day
    100
    A100
    MECH
    01/01/2013
    100
    A100
    MECH
    02/01/2013
    100
    A100
    MECH
    03/01/2013
    100
    A100
    MECH
    04/01/2013
    100
    A100
    MECH
    05/02/2013
    100
    A100
    MECH
    08/02/2013
    100
    A100
    MECH
    09/02/2013
    100
    A100
    MECH
    10/02/2013
    100
    A100
    MECH
    12/05/2013
    100
    A100
    MECH
    13/05/2013
    100
    A101
    CIV
    01/04/2013
    100
    A101
    CIV
    02/04/2013
    100
    A101
    CIV
    03/04/2013
    100
    A101
    CIV
    04/04/2013
    100
    A101
    CIV
    06/04/2013
    100
    A101
    CIV
    06/06/2013
    100
    A101
    CIV
    07/06/2013
    100
    A101
    CIV
    08/06/2013
    100
    A101
    CIV
    09/06/2013
    100
    A101
    CIV
    10/06/2013
    100
    A101
    CIV
    11/12/2013
    100
    A101
    CIV
    12/12/2013
    100
    A101
    CIV
    13/12/2013
    100
    A101
    CIV
    14/12/2013
        Dear friends this the sample table of my report.In which table has contain list of  employees with their working days(actual table has contain almost 5laks of records).
    suppose user choose the date between 01/01/2013 and 31/12/2013 then the result should be like this.
    comp_code
    emp_id
    dept_id
    month
    Total_work
    100
    A100
    MECH
    JANUARY
    4
    100
    A100
    MECH
    FEBRUARY
    2
    100
    A100
    MECH
    MARCH
    0
    100
    A100
    MECH
    APRIL
    0
    100
    A100
    MECH
    MAY
    2
    100
    A100
    MECH
    JUNE
    0
    100
    A100
    MECH
    JULY
    0
    100
    A100
    MECH
    AUGUST
    0
    100
    A100
    MECH
    SEPTEMBER
    0
    100
    A100
    MECH
    OCTOBER
    0
    100
    A100
    MECH
    NOVEMBER
    0
    100
    A100
    MECH
    DECEMBER
    0
    100
    A101
    CIV
    JANUARY
    0
    100
    A101
    CIV
    FEBRUARY
    0
    100
    A101
    CIV
    MARCH
    0
    100
    A101
    CIV
    APRIL
    5
    100
    A101
    CIV
    MAY
    0
    100
    A101
    CIV
    JUNE
    5
    100
    A101
    CIV
    JULY
    0
    100
    A101
    CIV
    AUGUST
    0
    100
    A101
    CIV
    SEPTEMBER
    0
    100
    A101
    CIV
    OCTOBER
    0
    100
    A101
    CIV
    NOVEMBER
    0
    100
    A101
    CIV
    DECEMBER
    4

    Hi,
    If you want the output to include months where no work was done (with 0 in the total_work column) then you need to outer-join a "table" that has one row per month, and make it a partitioned outer join:
    WITH  got_end_points   AS
       SELECT  TRUNC (MIN (work_day), 'MONTH')   AS first_month
       ,       TRUNC (MAX (work_day), 'MONTH')   AS last_month
       FROM    table_x
    ,   all_months   AS
       SELECT  ADD_MONTHS (first_month, LEVEL - 1)   AS a_month
       ,       ADD_MONTHS (first_month, LEVEL)       AS next_month
       FROM    got_end_points
       CONNECT BY  LEVEL <= 1 + MONTHS_BETWEEN (last_month, first_month)
    SELECT    t.comp_code
    ,         t.emp_id
    ,         t.dept_id
    ,         m.a_month
    ,         COUNT (t.work_day) AS total_work
    FROM             all_months  m
    LEFT OUTER JOIN  table_x     t  PARTITION BY (t.comp_code, t.emp_id, t.ept_id)
                                    ON   t.work_day  >= a.a_month
                                    AND  t.work_day  <  a.next_month
    GROUP BY  t.comp_code
    ,         t.emp_id
    ,         t.dept_id
    ,         m.a_month
    ORDER BY  t.comp_code
    ,         t.emp_id
    ,         t.dept_id
    ,         m.a_month
    As posted, this include every month that is actually in the table.  You can change the first sub-query if you want to enter first and last months.
    I hope this answers your question.
    If not, post  a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Point out where the query above is giving the wrong results, and explain, using specific examples, how you get the correct results from the given data in those places.  If you changed the query at all, post your code.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • Query  for getting records  max  reported  timestamp and 2nd max report

    query for getting records in between
    max reported timestamp and 2nd max reported timestamp
    HERE IS ALL RESULT SET
    TIME DOMAIN
    30:jun:2006:20:08:45 TOMCAT
    30:jun:2006:20:08:45 TOMCAT
    30:jun:2006:20:07:04 TOMCAT
    30:jun:2006:20:07:04 TOMCAT
    30:jun:2006:20:07:24 TOMCAT
    30:jun:2006:20:07:24 TOMCAT
    30:jun:2006:20:07:45 TOMCAT
    30:jun:2006:20:07:45 TOMCAT
    30:jun:2006:20:08:05 TOMCAT
    30:jun:2006:20:07:04 TOMCAT
    30:jun:2006:20:08:05 TOMCAT
    PD_REPORTED_TIMESTAM PD_USER
    30:jun:2006:20:08:25 TOMCAT
    30:jun:2006:20:08:25 TOMCAT
    30:jun:2006:20:08:45 TOMCAT
    30:jun:2006:20:08:45 TOMCAT
    30:jun:2006:20:07:24 TOMCAT
    30:jun:2006:20:07:04 TOMCAT
    30:jun:2006:20:07:24 TOMCAT
    30:jun:2006:20:07:45 TOMCAT
    30:jun:2006:20:07:45 TOMCAT
    30:jun:2006:20:08:05 TOMCAT
    30:jun:2006:20:08:05 TOMCAT
    PD_REPORTED_TIMESTAM PD_USER
    30:jun:2006:20:08:25 TOMCAT
    30:jun:2006:20:08:25 TOMCAT
    QUERY RESULT TO COME
    TIME DOMAIN
    TOMCAT 30:jun:2006:20:08:45
    TOMCAT 30:jun:2006:20:08:45
    TOMCAT 30:jun:2006:20:08:45
    TOMCAT 30:jun:2006:20:08:45
    Message was edited by:
    user517983

    Hi,
    can we write query like this.
    1 select pd_user,PD_REPORTED_TIMESTAMP
    2 from sp_process_detail_current spdc
    3 where host_id='DSCP02469'and pd_user='TOMCAT'
    4 and exists(
    5 select PD_REPORTED_TIMESTAMP from sp_process_detail_current
    6* having max(PD_REPORTED_TIMESTAMP)-spdc.PD_REPORTED_TIMESTAMP=0)
    SQL> /
    PD_USER PD_REPORTED_TIMESTAM
    TOMCAT 30:jun:2006:20:08:45
    TOMCAT 30:jun:2006:20:08:45
    TOMCAT 30:jun:2006:20:08:45
    TOMCAT 30:jun:2006:20:08:45

  • Need a query for export table data .....

    Hi,
    I need a query for exporting the data in a table to a file.
    Can anyone help me ?
    Thanking You
    Jeneesh

    SQL> spool dept.txt
    SQL> select * from dept;
        DEPTNO DNAME          LOC
            10 ACCOUNTING     NEW YORK
            20 RESEARCH       DALLAS
            30 SALES          CHICAGO
            40 OPERATIONS     BOSTON
    SQL> spool off
    SQL> ed dept.txt

  • Query creating duplicate records

    Hi
    I need to create a report that gives the po number, po line item number, material number and the delivery post code.
    I have created a query with the following tables:
    EKKO, EKPO, EBAN, VBEP, VBAK, VBPA, ADRC.
    I have deleted the wrong link between EKKO and EKPO and retained all other links as suggested.
    Could anybody let me know why there are duplicate records in the report pls?
    Thanks
    Desp09

    Desp09 wrote:
    Hi
    >
    > I have connected
    >
    > EKKO-EBELN to EKPO
    >
    >  EKPO -EBELN and EKPO-EBELP  to the same of EBAN
    >
    > also EKPO-BANFN and EKPO-BNFPO to the same of EBAN
    >
    > EBAN-BANFN and EBAN-BNFPO to VBEP
    >
    > VBEP-VBELN to VBAK-VBELn
    >
    > VBAK-VBELN to VBPA-VBELN
    >
    > VBPA-ADRNR to ADRC-ADDRNUMBER.
    >
    > This is the first time I have created a query so if you can kindly explain the logic of the error it would help in my future reports.
    >
    > Thanks
    > Priya
    Hi Priya,
    You can simplify the process if you make use of the LDB, which will fetch the same report with std LDB available in the system.
    You can define multiple infosets and  pull the fields for easier approach.
    Regards
    Shiva

  • Need different processes for Update and Delete buttons

    I'm using a customized version of the Issue Tracker sample application. I've added a table called project_person(project_id,person_id) so that a project can have multiple people assigned to it and so that one person can have multiple projects. I have a form report that lists all of the projects with an edit link which opens one project. On the individual project page, there are page items for each of the columns in the project table and a item for the person assigned to the project--this item is pulled from the separate project_person table. I have two buttons--Delete and Apply Changes. If you click on Apply Changes, the project table should be updated and then the project_person table if the assignment was changed. If you click on Delete, it should delete the project_person record first and then delete the project record. I created a new conditional pl/sql process that updated two tables if 'Apply Changes' button is cliicked. I then created a separate conditional process when the Delete button is clicked. This conditional process checks to see if a record in the project_person table exists, and if so, delete the record. Then delete the project record.
    The update process works fine. The delete process reloads the list of projects with a success message at the top without actually doing a delete and I have no idea why. Does anyone have any suggestions?
    I am not using the automatic row processing, but should I? Or is it ok to have the two separate conditions for the two different buttons?

    Hello again Miah,
    Check the "Sequence Number" for your processes. Typically, APEX will increment by 10, each time you create a Page Process as I recall. You can set this to be any number you want; even if you duplicate the sequence number (ie: you can have multiple Sequence 10 processes).
    Make sure that your Delete process is firing properly and walk through the logic in the source code to be sure that any "IF" or "WHERE" logic is satisfied. For example:
    Begin
      delete from emp_table
        where 1=2;
    End;If this was your page process code - you would receive a SUCCESS message because the PL/SQL code executed successfully, even though nothing will be deleted since 1 will NEVER equal 2.
    So, check Delete Source carefully.
    {size:14}{color:green}Can you post the code from your delete page process here?{color}{size}
    Good luck,
    Don.
    REWARDS: Please remember to mark helpful or correct posts on the forum, not just for my answers but for everyone! :)
    Edited by: dfcii© on Oct 27, 2009 10:55 AM

  • How  to fire a query for every record in a table, pass values in a loop

    Hi,
    For each record in a table, I want to loop through each record and then fire a query by passing acct, product and date from this table to the where clause of the query. I would have to create a pl/sql block..The output of the query I want to spool from sql developer.
    I need the exact syntax please for doing this.. since i am new to Oracle. Just the template will be enough. I will fill in the query.
    Any help is appreciated as always..
    Regards,
    hena

    904385 wrote:
    Hi,
    For each record in a table, I want to loop through each record and then fire a query by passing acct, product and date from this table to the where clause of the query. I would have to create a pl/sql block..The output of the query I want to spool from sql developer.
    I need the exact syntax please for doing this.. since i am new to Oracle. Just the template will be enough. I will fill in the query.
    Any help is appreciated as always..
    Regards,
    henaHave you ever considered using a JOIN ? It does the same thing as looping through a table and applying that to the where clause of a select on a query, only much, much, much faster and without the need to write any code. SQL is a declarative language, so you specify what you want and not how to do it. It can be bit of a journey to change your thought process if you come from a procedural or object world, but once you get there it's a beautiful view.

  • Writing OR query for fetching records

    Hi,
    I have dowloaded a custom wsdl and generated a java client from it using Jdeveloper.
    I have a method named customObject1QueryPage(QueryInputObj) which is used to query the CRM oD to fetch records.
    I have successfully queried using the above method for one condition:-
    QueryInputObj param= new QueryInputObj();
    QueryType q = new QueryType();
    q.set_value("='" + "ABC'");
    //q.set_value("LIKE 'A*'");
    param.setAccountName(q);
    customObject1QueryPage(param);
    But now I want to query using "OR" condition with multiple names in the condition and I don't know how to
    write query for that.
    SQL query would be like "Select * from table where name='ABC' OR name='PQR' OR name ='XYZ' ";
    I want to execute same query for CRM oD but have no idea how to write it.
    Can somebody please help me as soon as possible.
    Thanks.

    Hi,
    If your intent to Use OR Condition on a field with multiple Values
    say, AccountName = 'xyz' OR AccountName= 'abc' the syntax would be *(='xyz') OR (='abc')*
    say, AccountName = 'xyz' OR AccountName= 'abc' OR AccountName = 'pqr' the syntax would be *((='xyz') OR (='abc'))OR(='pqr')*
    You can find similar example under On Demand Web Service Documentation
    Regards
    Deepak H Andeli

  • Searching for Duplicates records in Qualified Lookup tables

    Hi SDNers,
    I would like to know,
    How to find out how many records having duplicate records in Qualified Look Tables.
    In Free form search or Drill down Serach.. I am select the particular Qualified Look up Table. After how can I find Duplicated reocrds.
    Any Solution?
    Thanks
    Ravi

    Hi,
    If you want to find the duplicates present in qualified table then, you can go to qualified table in data manager and get to know the duplicates....else if you want to find the duplicate links to a record in main table, then you can write an expression in free form search to get the value of duplicate links. but that would be specific to a link value only..e.g. Country is your no qualifier, then in free form search, you can write an expression to get how many links are for USA.
    Hope this clarifies your doubt...if not, please elaborate on the requirement.
    Regards,
    Arafat.

  • Need a Query for getting ItemCost from PO Vendor wise

    Hi,Experts We are not maintain different price list for  some particular items , We raised the PO for Multiple vendors with differnt price for the same material. We need a query to find the Item cost with Various Vendor .
    I need the query in the following format
    Po Number, Vendor Name,Item Name, Item Description,Qty, Price,Tax.
    Thanks
    Kamal

    Hi,
    Check this query which looks for the Item doctype Purchase Order and brings the data accordingly :
    select t0.docnum as 'PO Number', t0.CardName as 'Vendor name', t1.itemcode as 'Item Name',
    t1.Dscription as 'Item Description', t1.quantity as 'QTY', t1.Price as 'Price',
    t1.vatsum as 'Tax Amount'
    from OPOR t0 inner join POR1 t1 on t0.docentry = t1.docentry
    where t0.doctype ='I'
    Group by t1.itemcode, t1.Dscription, t0.docnum,
    t0.cardname, t1.quantity, t1.Price, t1.vatsum
    Order by t1.Itemcode
    Check if it helps.
    Kind Regards,
    Jitin
    SAP Business One Forum Team

  • Need a query for access tables

    Hi
    I need a query , help please:
    table1:
    id              description                  serial                    
    1                des1                           ser1
    2                des2                           ser2
    3                des3                           ser3
    table2:
    id            id1(id of table1)                date                
    stat
    1              1                                      
    2001                 A
    2              1                                      
    2008                 N
    3              2                                      
    2010                 A
    4              1                                      
    2012                 F
    ==============
    i need this data structure: (stat column must return for maximum date of id1 from table2)
    id(from table1)            serial(from table1)                  stat(from table2)
    1                                    ser1                
                           2012
    2                                    ser2             
                              2010
    3                                    ser3             
                               Null

    maybe you can try this.
    declare @t1 table
    (id int,[description] varchar(50),serial varchar(10))
    declare @t2 table
    (id int,id1 int,[date] char(4),stat char(10))
    insert into @t1 values
    (1,'des1','ser1'),
    (2,'des2','ser2'),
    (3,'des3','ser3')
    insert into @t2 values
    (1,1,'2001','A'),
    (2,1,'2008','N'),
    (3,2,'2010','A'),
    (4,1,'2012','F')
    select a.id,a.serial,max(b.date)
    from @t1 a
    left join @t2 b
    on a.id = b.id1
    group by a.id,a.serial
    | SQL PASS Taiwan Page |
    SQL PASS Taiwan Group
    |
    My Blog

  • Help needed in query for Materialized View

    Hi,
    I want to create a materialized view which has some precalcultaed values.
    I have four dimension tables out of which one is a Time Dimension table with levels as Year->Quarter->Month.
    The precalculations are the moving averages and cummulative values of Sales Amt on the dimension values over a period of 4 Months.
    The dimension tables are Clients, Products, Channel, Time.
    Fact Table is Sales_Fact which will have the sales amount for different members of the dimension.
    Since my fact table is very huge, i want to create a materialized view where i could store the required calculated measures, here Moving Average of Sales Amt for each Client, Product, Channel dimensions over a period of 4 Months.
    Can anybody help with writing the query for this..Any help in this regard will be appreciated..
    Please give me suggestions for this..

    Check this link.
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14223/aggreg.htm#sthref1612
    Regards
    Raj

  • Alternative/enhancement to union query? Duplicate - please delete

    Hello,
    I have 2 sets of similar data which I am joining together with a union query.
    Simplified E.g.
    *Table A*
    Name Dept
    Ben    1
    Amy   3
    Ken    3
    *Table B*
    Name Dept
    Jim    1
    John  2
    Sue   3
    select Name, Dept
    from table A
    UNION
    select Name, Dept
    from table BWhat I would like to do is ONLY include data from the second part of the union query where it joins with some data from the first part of the union query.
    E.g.
    select Name, Dept
    from table A
    UNION
    select Name, Dept
    from table B
    where Dept in (select distinct Dept from A)Therefore John that works in Dept 2 would not be included in the results.
    Is there a better or more efficient way of doing this than my example using the subquery as part of the where clause?
    Many thanks,
    Hazel
    Edited by: user11979866 on 04-Nov-2010 08:48

    Hazel:
    It would really depend on the sizes of the tables and the indexes available, but that is probably the way I would write it, at least as a first cut.
    You could lose the distinct in the in sub-query since it is implied by the in itself, and Oracle will only return one row from the sub-query for each value of dept in A.
    John

Maybe you are looking for