Selecting single dataset from multiple datasets based on prioritized column

I apologize if a similar question has been answered before. I don't seem to find to the correct search terms to find the solution.
On to the question - I have the following data:
+---ItemID---+---ItemName----------------------+---CompanyID---+
|    1001    | Item  1001                      |       1       |
|    1001    | Tuote 1001                      |       2       |
|    1001    | Artikel 1001                    |       3       |
|    1002    | Item  1002                      |       1       |
|    1002    | Artikel 1002                    |       3       |
|    1150    | Tuote 1150                      |       2       |
|    2000    | Item  2000                      |       1       |
|    2000    | Tuote 2000                      |       2       |
|    2222    | Tuote 2222                      |       2       |
|    2222    | Artikel 2222                    |       3       |
+------------+---------------------------------+---------------+
with t as (
        select 1001 ItemID, 'Item  1001' ItemName, 1 CompanyID from dual union all
        select 1001,    'Tuote 1001',   2 from dual union all
        select 1001,    'Artikel 1001', 3 from dual union all
        select 1002,    'Item  1002',   1 from dual union all
        select 1002,    'Artikel 1002', 3 from dual union all
        select 1150,    'Tuote 1150',   2 from dual union all
        select 2000,    'Item  2000',   1 from dual union all
        select 2000,    'Tuote 2000',   2 from dual union all
        select 2222,    'Tuote 2222',   2 from dual union all
        select 2222,    'Artikel 2222', 3 from dual
select
from
    tAs you can see, not all companies contain the same items. I would need to get a list which contains each itemid only once, and item name (and other fields not visible in the example) from the first company in which the item is found. The priority would be CompanyID 1, 3 and lastly 2. So the above example would result in the following list:
+---ItemID---+---ItemName----------------------+---CompanyID---+
|    1001    | Item  1001                      |       1       |
|    1002    | Item  1002                      |       1       |
|    1150    | Tuote 1150                      |       2       |
|    2000    | Item  2000                      |       1       |
|    2222    | Artikel 2222                    |       3       |
+------------+---------------------------------+---------------+

Hi,
That's called a Top-N Query , and here's one way to do it:
WITH     got_r_num   AS
     SELECT     ItemID, ItemName, CompanyID
     ,     ROW_NUMBER () OVER ( PARTITION BY  ItemID
                               ORDER BY          CASE  CompanyID
                                               WHEN  1  THEN  1
                                    WHEN  3  THEN  2
                                    WHEN  2  THEN  3
                                         END
                             ) AS r_num
     FROM    t
--     WHERE     ...     -- Any filtering goes here
SELECT     ItemID, ItemName, CompanyID
FROM     got_r_num
WHERE     r_num     = 1
;The tricky part here is getting an expression that will sort the CompanIDs in the order in which you want them (3 comes before 2). If that order applies to other queries besides this one, then you should really not hard-code it into any query. Instead, add a column to the company table (or create a company table, if you don't already have one), that indicates the sort order, and join to that table.
The aggregate KEEP (DENSE_RANK ...) feature could also be used to get these results, but you mentioned that there were "other fields not visible in the example", which means you would probably have to repeat a fairly complicated expression for each one of them. The query above is easily extended; add whatever columns you want to both SELECT clauses.
Edited by: Frank Kulash on Jun 21, 2010 4:41 PM

Similar Messages

  • Selecting single record from multiple record based on date

    Hi experts,
    I have a table which contains the multiple records for single ID No. Now i have to select single record which contains the latest date.
    here is the structure
    Name   Null Type        
    ID_P        NUMBER      
    NAME_P      VARCHAR2(12)
    DATE_P      TIMESTAMP(6)
    Records
    1 loosi     22-AUG-13 01.27.48.000000000 PM
    1 nammi  26-AUG-13 01.28.10.000000000 PM
    2 kk        22-AUG-13 01.28.26.000000000 PM
    2 thej      26-AUG-13 01.28.42.000000000 PM
    now i have to select below 2 rows how can write select qurie for this?
    1 loosi     26-AUG-13 01.27.48.000000000 PM
    2 thej      26-AUG-13 01.28.42.000000000 PM

    Hi,
    You can use the analytic ROW_NUMBER function.
    I don't have a copy of your table, so I'll use scott.emp to illustrate.  In scott.emp, there may be multiple rows for a single job.  To display just 1 row per job, the row with the most recent hiredate:
    WITH got_r_num AS
         SELECT  empno, job, deptno, hiredate -- Or whatever columns you want
         ,       ROW_NUMBER () OVER ( PARTITION BY  job
                                      ORDER BY      hiredate DESC
                                    )  AS r_num
        FROM    scott.emp
    --  WHERE ...   -- If you need any filtering put it here
    SELECT   *      -- Or list all columns except r_num
    FROM     got_r_num
    WHERE    r_num   = 1
    What results do you want in case of ties?  Depending on your requirements, you may want to add tie-breaking expressions to the analytic ORDER BY clause, and/or use RANK instead of ROW_NUMBER.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    Point out where the query above is producing the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
    If you modify the query at all, post your modified version.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • Split single row in multiple rows based on date range

    I need sql script that can split single row in multiple rows based on start date and end date column in table.
    Thank you

    I agree to your suggestion of having a dates table permanently in the database. Thats how we also do for most of our projects as well
    But in most projects the ownership  of table creation etc lies with the client as they will be the DBAs and will be design approval authorities. What I've seen is the fact that though
    many of them are in favour of having calendar table they dont generally prefer having a permanent table for numbers in the db. The best that they would agree is for creating a UDF which will have
    tally table functionality built into it based on a number range and can be used in cases where we need to multiply records as above.
    Wherever we have the freedom of doing design then I would also prefer creating it as a permanent table with required indexes as you suggested.
    >> many of them are in favour of having calendar table they dont generally prefer having a permanent table
    Those people do not understand about database and are not DBAs :-)
    It is our job to tell them what is right or wrong.
    ** This is a real story! I had a client several years back, who was the CEO of a software company.
    He use the query:
    select * from table_name
    In order to get the last ID!
    The table_name was actually a view that took data from several tables, and the main table that he wanted to get the ID included several string columns, with lot of data!
    he actually pulled all this data to the application, just to get the lat ID in a specific table!
    It is our job as Consultants or DBAs to fix's his misunderstanding :-)
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • How can I create a single order from multiple quotations?

    How can I create a single order from multiple quotations that I have created by the transaction VA21 ?
    Thanks in advance for the answers.

    hi
    Go to transaction: /nva01
    Enter order type : ZOR
    Sale org :xxxx
    Dist.channel:xx
    Division :xx
    Press enter
    Click on “Sale document” and select Create with reference
    Then enter 1st quotation number & click on “COPY” or “Selection list”. Then click on “Copy “.Then all line items which belong to quoation1 copy to order.
    Then,
    Click on “Sale document” and select Create with reference
    Then enter 2nd quotation number & click on “COPY” or “Selection list”. Then click on “Copy “.Then all line items which belong to quoation2 copy to order.
    Then,
    Click on “Sale document” and select Create with reference
    Then enter 3rd quotation number & click on “COPY” or “Selection list”. Then click on “Copy “.Then all line items which belong to quoation3 copy to order.
    Now save the sale document.
    Kindly give reward points
    Edited by: WISH on Mar 19, 2008 2:25 PM

  • How can i select some row from multiple row in the same group of data

    I want to select some row from multiple row in the same group of data.
    ColumnA        
    Column B
    1                  OK
    1                   NG
    2                   NG
    2                          NG
    3                          OK
    3                          OK
    I want the row of group of
    ColumnA if  ColumnB contain even 'NG'
    row , select only one row which  Column B = 'NG'
    the result i want = 
    ColumnA         Column B
    1                         NG
    2                   NG
    3                          OK
    Thank you

    That's some awful explanation, but I think this is what you were driving at:
    DECLARE @forumTable TABLE (a INT, b CHAR(2))
    INSERT INTO @forumTable (a, b)
    VALUES
    (1, 'OK'),(1, 'NG'),
    (2, 'NG'),(2, 'NG'),
    (3, 'OK'),(3, 'OK')
    SELECT f.a, MIN(COALESCE(f2.b,f.b)) AS b
    FROM @forumTable f
    LEFT OUTER JOIN @forumTable f2
    ON f.a = f2.a
    AND f.b <> f2.b
    GROUP BY f.a

  • Can i create a single image from multiple images in lightroom?

    Can i create a single image from multiple images in lightroom?

    Like a panorama, a composite or focus stack? Have you tried the Lightroom forum?
    Photoshop Lightroom

  • Any Tutorial / Sample to create Single PDF from multiple source files using PDF assembler in a watched folder process.

    Any Tutorial / Sample to create Single PDF from multiple source files using PDF assembler in a watched folder process. I have a client application which will prepare number of source files and some meta data information (in .XML) which will be used in header/footer. Is it possible to put a run time generated DDX file in the watch folder and use it in Process. If possible how can I pass the file names in the DDX. Any sample Process will be very helpful.

    If possible, make use of Assembler API in your client application instead of doing this using watched folder. Here are the Assembler samples :  LiveCycle ES2.5 * Programming with LiveCycle ES2.5
    Watched folder can accept zip files (sample : Configuring a watched folder to handle multiple input files and write results to a single folder | Adobe LiveCycle Blog ). You can also use execute script to create the DDX at runtime : LiveCycle ES2 * Application Development Using LiveCycle Workbench ES2
    Thanks
    Wasil

  • How do I create. A single PDF from multiple files? PDF pack on iOS

    How do I create. A single PDF from multiple files? PDF pack on iOS
    The primary reason I signed up for. PDF Pack was to create a single PDF from multiple image files and other PDFs .
    Is this possible? If so how
    thanks in advance
    rich

    Hi Rich,
    The combine files feature isn't available when you're using Reader for iOS. However, you can log on to the web interface at Adobe Acrobat.com using your Adobe ID and credentials, and use the Combine Files feature there.
    Please let us know if you need further assistance.
    Best,
    Sara

  • Single delivery from multiple Sales Orders

    Can you let me know how to create a Single DN if there are different parts to be shipped if the below satisfies,
    same ship-to-party
    same ship date
    thx,

    Hi Pri,
    To have single delivery from multiple Sales Orders you have 2 waysto do it.
    The prerequisites are,
    A. All sales orders should have same ship to Party
    B. Delivery due dates should be same.
    C. Incoterms should also be same.
    D. Shipping Point should be same.
    Once this is ensured, you can either
    1. Go to Tr. Code VL10A and execute the delivery document creation for the list of sales orders
    Or,
    2. Go to VL01N. Give 1st order no. enter into the overview screen
    Here, go to main menu, Outbound Delivery ---> Collective Processing- Del. Creation
    This will also take u to the same VL10A screen.
    Hope, this is helpful. Award points if found helpful.
    Regards,
    Niketan

  • Does OBIEE has ability to create a single cube from multiple data sources?

    Hi all,
    Does OBIEE has the ability to create a single cube from multiple sources and does it has the ability to join multiple cubes?
    Looking forward to ur reply.

    Hi
    OBIEE can join multiple data sources to make a single data model, but it's not a cube in the multi-dimensional sense like Essbase or Oracle OLAP.
    To be able to join datasources together they need to have a common dimension or FK relationship depending on what the source is and what you want to do with it.
    Ed

  • Multi-file Loading Single Package from Multiple Agents?

    hi,
    i am trying to load the Multiple files from(Interface-Load Multiple file to Oracle DB) a package. as this activity is done multiple loading files Name from single table.
    I just want to know that is there any solution to execute the single Package from Multiple Agents for Load Balancing from Single table. & if YES then refer any document????
    Regards,
    AMSII

    done.resovlesd my self

  • Select single time printer & multiple PR should come through that printer

    Hi friends,
    I am calling smartform in loop to print multiple Purchase Requisition. End user wants to select single time printer & multiple Purchase Requisition should come through that printer.
    I am calling my Smartform in a LOOP.
    How I will resolve this issue.
    Regards,

    Hi,
    Instead of driver programme write loop statement in the smartform.
    Aswarth

  • Picking files from multiple folders based on name send to destination folde

    Hi,
       I want to pick multiple files from multiple folders with one root folder. Based on file name I want to send it to diffirent folders. No need to go for message mapping. Can anyone suggest me.
    Thanks & Regards,
    Prasad Kotla.

    Hi Prasad,
    to pick the files from multiple source directory, can use "Advance Selection for Source File" in Sender CC.
    If you wand to develop a Scenario without Message mapping, develop a scenario as "Sender as Virtual receiver"
    This option is available in Sender agreement, just give the dummy name for Msg Interface and Namespace, Name defined should be same in Rec Agreement.
    Develop only: Sende CC, Receiver CC, SA, RA
    No need to develop ID and RD as no mapping is involved.
    If u want to send the files to different folders of receiver side, just develop the adapter module which changes the directory based on the sender filename.
    If the sender and receiver directory is same than check the "adapter specific Msg Attribute"  and "directory" checkbox in both the sender and receiver CC. in this case no need to develop Custom module for changing the directory. files will be automatically placed in the path they were picked from  sendor directory
    appreciate if useful
    regards,
    chandra shekhar

  • Splitting the single record into multiple records based on validity

    Hi Guru's,
    basically i am an BI consultant with less knowledge on ABAP, can i request your help on the ABAP task.
    I am working on HR module which is integrated with SAP BI,  the reports will be executed based on calendar month the requirement is i should split the single record into a multiple records based on validity of the record.  basically the HR data would be in data from and date to. 
    below is the logic
    Check whether the start and end date of the record are in the same month and year.
    If yes  nothing changes
    If no  create multiple records
    1st record  original start date of the record u2018till end of that month
    Following record  1st of the next month  u2018till last day of the month
    u2026
    Last record  1st of the month u2018till original end date.
    All fields will have the same values, only the datefrom and dateto fields change.
    Can any one please provide me the same code to proceed on my task.
    Thanks and Regards,
    Venkat

    Hi,
    Using Rule group we can split it.
    Using Rule Group in SAP-BI  Part - 1
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/business-intelligence/s-u/using%20rule%20group%20in%20sap-bi%20%20part%20-%201.pdf
    Thanks
    Reddy

  • How to select photo's from multiple locations in Places view?

    I want to select photos from multiple locations (close to eachother) in Places view (shift-P). I tried clicking to pins with cmd-click, but that did not work. They turn yellow, but that does not select the photos from that location.
    Koen

    Found the answer myself
    Yellow pins select the photos from that location, whereas clicking the arrow on the balloon above the pin creates a filter for photos from that location.
    Koen

Maybe you are looking for

  • Replace OUTLOOK HOME AND BUSINESS Version with OUTLOOK PROFESSIONAL [Standalone]

    Hey Techies, Here is the Scenario,I have been using Office Home and business 2013(installed from Click-to-run setup)  on my WIN-7 pro. As i needed to access my Microsoft Exchange online archive (i have exchange online plan 2) on Outlook i'd to buy ou

  • Supress Column Heading - File Content Conversion in Sender Adapter

    Hi, Let me give a more clear picture about my scenario.  I need to convert CSV File to XML output:- My source file has column heading and values.  The sample data is mentioned hereunder:- PERNR;KID;PNALT;NACHN;NAME2;VORNA ;1200;1200;Angus I have crea

  • Using PL/SQL in OMS Reports

    I've written a pl/sql block report and I'd like to add it to the OMS reports. Are there any examples or hints on how to do this ? Thanks

  • Ticker Control errors

    Hi all, I have use the ticker control, I have inserted my formula and I have deployed my model. The ticker shows correctly the data that I set in the formula but at run time the iView display a second row with the field ID as label and the data of my

  • HP 15.6" G56-129WM Laptop PC with Intel Celeron 900 Processor & Windows 7 Home Premium

    My computer is really slow... I've tried restarting it to the manufuture setting, but it didn't really work . It is a bit faster but its still really slow. It runs slow even when just having one google chrome/ internet experor site.  What could the p