SELECT generate records

Hello guys, I have some difficulty in writing of a SELECT statement. I opened a discussion on a subject like this one a few weeks ago.

But, since I closed it, I reopen a new. Imagine the following scenario. I have a table with the documents, another with an attachment and a junction between these two table. Documents and attachments can have different version. There is a technique used for the foreign key id and the id of commercial real is the combination between document_id and version (even in version and attachment whith attachment_id).

It is a simplified version of my reality... But let's concentrate on this simple scenario.

-- The technical id is used for foreign keys. 
-- [document_id is a business key and the combination of document_id version is unique]
CREATE TABLE documents 
(
  technical_id NUMBER(10), 
  document_id number(10),
  version number(10),
  title varchar2(100)
);


CREATE TABLE attachments
(
  technical_id number(10), -- primay key 
  attachment_id number(10),  -- concat of attachment_id and version is unique!
  version number(10),
  language varchar2(100),
  title varchar2(100)
);


CREATE TABLE doc_attachments
(
  document_id number(10),
  attachment_id number(10)
);

Now, imagine the following inserts.

INSERT INTO documents(technical_id, document_id, version, title) VALUES(1, 1, 1, 'document 1 (version 1)');
INSERT INTO documents(technical_id, document_id, version, title) VALUES(2, 1, 2, 'document 1 (version 2)');
INSERT INTO documents(technical_id, document_id, version, title) VALUES(3, 1, 3, 'document 1 (version 3)');


INSERT INTO attachments(technical_id, attachment_id, version, language, title) VALUES(99, 10, 1, 'fr', 'attachment 10 (version 1)');
INSERT INTO attachments(technical_id, attachment_id, version, language, title) VALUES(98, 10, 1, 'en', 'attachment 10 (version 2)');
INSERT INTO attachments(technical_id, attachment_id, version, language, title) VALUES(97, 10, 2, 'fr', 'attachment 10 (version 3)');


INSERT INTO doc_attachments(document_id, attachment_id) VALUES(1, 99);
INSERT INTO doc_attachments(document_id, attachment_id) VALUES(1, 98);


INSERT INTO doc_attachments(document_id, attachment_id) VALUES(3, 97);

In this scenario,.

-J' have version 3 of the same document.

-Two different attachments; one of them has two version.

-3 links between documents and attachments.

If you pay attention, you will notice that I have no connection between the attachment and the second version of the document. And also, I have different languages for the same attachment. In this scenario, I want to the next exit. The list of all versions of a document with their attachments (all languages) and "gaps" with attachments previous.

The logic is a bit tricky to understand the output. Basically, for each document, I want to see all the 'last home"received for this folder. Later we hear the fixation with the largest number of version for the same id of attachment.

doc_tech_id doc_version attac_tech_id attachment_version language
----------- ----------- ------------- ------------------ -------- 
         1            1            99                  1       fr -- the first and second insert are generating these two first output records.
         1            1            98                  1       en 


         2            2            99                  1       fr -- since I did not have any link between the second version of the doc and the attachment, 
         2            2            98                  1       en -- I should have exactly the same as the previous version. So I duplicate records.
         
         3            3            97                  2       fr -- I have a link in the join table between document in version 3 and the second version of the attachment.
         3            3            98                  1       en                     

It is a scenario... I wonder if this is doable in a single query? Can someone help me?

Thank you

with

documents such as

(select 1 technical_id, 1 document_id, version 1, title "document 1 (version 1)" of all the double union)

Select 2,1,2, "document 1 (version 2)" dual Union all

Select 3,1,3, "document 1 (version 3)" of the double

),

As spare part

(select 99 technical_id, 10 attachment_id, 1 version, language 'fr', "attachment 10 (version 1)" title of all the double union)

Select 98,10,1, 'FR', "attachment 10 (version 2)" dual Union all

Select 97,10,2, 'fr', "attachment 10 (version 3)" of the double

),

doc_attachments as

(select 1 document_id, 99 attachment_id union double all the)

Select 1.98 Union double all the

Select double 3.97

)

Select the language, attac_tech_id, doc_tech_id, attac_version, doc_version

from (select doc.technical_id, doc_tech_id,

doc.version doc_version,

ATTS.technical_id attac_tech_id,

ATTS.version attac_version,

ATTS. Language,

ROW_NUMBER() over (partition doc.technical_id, atts.language, doc.version

order by case when doc.version = 3 then atts.version to another atts.technical_id end desc

) rn

document No.

left outer join

doc_attachments x partition by (x.attachment_id)

On x.document_id = doc.technical_id

inner join

Spare atts

On x.attachment_id = atts.technical_id

)

where rn = 1

DOC_TECH_ID DOC_VERSION ATTAC_TECH_ID ATTAC_VERSION LANGUAGE
1 1 98 1 en
1 1 99 1 en
2 2 98 1 en
2 2 99 1 en
3 3 98 1 en
3 3 97 2 en

the order by clause appears to produce the result you expect, but I can't explain why it should be applied

Concerning

Etbin

Tags: Database

Similar Questions

  • How to select a record in one table to manipulate data in a database?

    Hello community,

    Using 32-bit Labview 2015.

    I created a user interface that runs a query and retrieves my table from a sql database.

    I want to be able to manage only one record at a time by selecting the record in my table and then manipulate the data according to the needs.

    Whenever the user runs a query, I want as the first record in the table to be selected / highlighted.

    I want an indicator that is currently active.

    Then a click of a button, to be able to scroll the actively selected record.

    Once I have the selected record, I want a way to write a query to edit or delete the record.

    Is attached a photo of my query to select all of my table and connect data in my table (results).

    Attached a photo of my painting showing the timeline of my sql database.

    What is the best way to go on a record selection in a table and the modification of data with a query?

    Any help would be greatly appreciated.

    Thank you

    I guess that's not a table, but multi-column listbox.

    Right click, select--> highlight whole line selection Mode

    The value of the multicolumn listbox is the row index - you can write a local variable to highlight the line, the event structure to handle the user clicking on, etc.

    If you enable the property editable ListBox cells, you can allow users to edit the items of the listbox.

    If you want to get the data in row, you hint REF table and work with the array of strings in row - convert it to cluster, etc..

    I don't know, what type of data, it is, how you structure the database looks like, I don't even know if you use the wrapper to work with the database, I can't write queries for you.

    Something like Update Tablica Set Serial = '5' where ID = '22';

  • record selector don't work for the specific selection of records

    Hello

    I have a problem with the record selector in the spotlight.

    I want to select specific record, but when I select the control in the record are not in the selected record tab!

    the dataservice.json and endecaBrowserService.json files are correctly set up I think. I compare it with the app to Discover, but I do not want would be the question! not that the dynamic selection of records are working properly

    endecaBrowserService.json

    {

    "host': 'W177."

    "port": "15101."

    "recSpecProp": "Product_SKU",

    "recAggregationKey": "Endeca_Rollup_Id",

    "recFilter",:

    "recImgUrlProp": "URL_Thumbnail1",

    'recDisplayProps': ['brand', 'Category_EN', 'Product_SKU'],

    "textSearchKey": "interface_EN",

    'textSearchMatchMode': 'ALLPARTIAL '.

    }

    DataService. JSON

    {

    "jcr:primaryType': ' short: unstructured."

    "host': 'W177."

    "port": "15101."

    "recordSpecName": "Product_SKU",

    "aggregationKey": "Endeca_Rollup_Id",

    «recordFilter ": «,»

    'wildcardSearchEnabled': false,

    "recordNameField": "product_name_en",

    "fields": {"Brand": "', 'Category_EN': '',' Product_SKU'": ""}

    }

    any idea

    Thank you

    What is the record specification for records that fail?  For example, I found that the editor will fail if the record ID have spaces. That is to say 'Id1 Id2'.  Our resolution after conferring with support is to add an underscore 'Id1_Id2 '.

  • Multiple selection of records in table advanced to update in the Search Page.

    Hi all

    I write the code below, to select multiple records in table advanced for the update after clicking on the button update in the Search Page.
    I write this code in Processform request, but I got the exception when I run the code below.


    If (PageContext.GetParameter ("UpdateOnSeaBtn")! = null)
    {
    Am = (XxSupppacklistAMImpl) pageContext.getApplicationModule (webBean) XxSupppacklistAMImpl;
    am.saveRollback ();
    OAViewObjectImpl upDtVO = (OAViewObjectImpl) am.findViewObject ("PackingListSeaVO");
    PackingListSeaVORowImpl line;

    HashMap vParm = new HashMap();

    Row [] rows = upDtVO.getFilteredRows ("SingleSelection", "Y");
    int fetCount = upDtVO.getRowCount ();
    System.out.println ("Teh recovered rowcount is:," + fetCount);

    RowSetIterator multiIter;
    multiIter = upDtVO.createRowSetIterator ("multiIter");
    multiIter.setRangeStart (0);
    multiIter.setRangeSize (fetCount);


    for (int i = 0; i < fetCount; i ++)
    {
    Row = (PackingListSeaVORowImpl) multiIter.getRowAtRangeIndex (i);
    If (Row.GetAttribute ("SingleSelection")! = null)
    {
    If (Row.GetAttribute ("ItemNumber")! = null)
    {
    Object vitemNum = row.getAttribute ("ItemNumber");
    System.out.println ("The selected element Num is:," + vitemNum);
    vParm.put ("ItemNumber", vitemNum);

    pageContext.setForwardURL ("OA.jsp?page=/xxfls/oracle/apps/po/packlist/webui/XxSuppalistcrealistPG", / / here, I got the exception below)
    NULL,
    OAWebBeanConstants.KEEP_MENU_CONTEXT,
    NULL,
    vParm,
    false, / / RetainAM
    OAWebBeanConstants.ADD_BREAD_CRUMB_NO,
    OAWebBeanConstants.IGNORE_MESSAGES);
    }
    }
    }

    multiIter.closeRowSetIterator ();

    }
    }
    }

    could you, please, can someone help on this.


    I got below exception to the side server when it is run the code above.
    Error (125,48): method setForwardURL (java.lang.String, null, null, byte, java.util.HashMap, boolean, java.lang.String, byte) is not not in the interface oracle.apps.fnd.framework.webui.OAPageContext

    Kind regards

    Hello

    832859 wrote:

    for (int i = 0; i)<>
    {
    Row = (PackingListSeaVORowImpl) multiIter.getRowAtRangeIndex (i);
    If (Row.GetAttribute ("SingleSelection")! = null)
    {
    If (Row.GetAttribute ("ItemNumber")! = null)
    {
    Object vitemNum = row.getAttribute ("ItemNumber");
    System.out.println ("The selected element Num is:," + vitemNum);
    vParm.put ("ItemNumber", vitemNum);

    > pageContext.setForwardURL"OA.jsp.page=/xxfls/oracle/apps/po/packlist/webui/XxSuppalistcrealistPG",//here I got below exception

    NULL,
    OAWebBeanConstants.KEEP_MENU_CONTEXT,
    NULL,
    vParm,
    false, / / RetainAM
    OAWebBeanConstants.ADD_BREAD_CRUMB_NO,
    OAWebBeanConstants.IGNORE_MESSAGES);
    }
    }
    }

    -Here is you call pageContext.setForwardURL loop.
    >

    I got below exception to the side server when it is run the code above.
    Error (125,48): method setForwardURL (java.lang.String, null, null, byte, java.util.HashMap, boolean, java.lang.String, byte) is not not in the interface oracle.apps.fnd.framework.webui.OAPageContext

    -check 5th param should nt be vParm if it is null

    Finally... After the for loop ends call... y bcz assume this page grouped 10 rows can he navigate both on the next page...:

    pageContext.setForwardURL ("OA.jsp?page=/xxfls/oracle/apps/po/packlist/webui/XxSuppalistcrealistPG",
    NULL,
    OAWebBeanConstants.KEEP_MENU_CONTEXT,
    NULL,
    NULL,
    false, / / RetainAM
    OAWebBeanConstants.ADD_BREAD_CRUMB_NO,
    OAWebBeanConstants.IGNORE_MESSAGES);
    }

    Concerning
    Meher Irk

    Published by: Meher Irk on March 31, 2011 19:54

  • By selecting certain records by using the check box

    Hello

    I have a similar problem mentioned in this thread Re: select specific records using the checkbox I got if I have only one primary key value in the work table. I don't know how to handle it when I have several primary keys of the table I want to use for filtering?

    Thank you.

    Hello

    You can use rowid
    First report

    SELECT APEX_ITEM.CHECKBOX(1,e.rowid) chk,
    e.*
    FROM emp e
    

    Use even submit after processes.
    And target page report

    SELECT e.*
    FROM emp e
    WHERE EXISTS(
    SELECT 1
    FROM apex_collections c
    WHERE c.collection_name = 'P46COL'
    AND c.c001 = e.rowid)
    

    Kind regards
    Jari

    Published by: jarola on October 14, 2010 10:50

  • Selection of records over 90 days

    Can someone tell me a way to select all records that are older than 90 days? I have a field named PostedDate which is the date that the record was created. I use MS Access.

    Thank you!

    Copy the following code:

    Select * from employee where startdate<>

    This means:

    Select * from employee where startdate<>

  • Impossible to select the recording device in Audacity

    Audacity preferences

    In Audio i/o in Audacity my tent to follow preferences set up the tutorial, the recording device box sucks a selection. Is it because my headphones is not connected at this time? However, just like in the tutorial section playback device IS first filed with the phrase OUTPUT of MAPPING MICROSOFT SOUND. What is c? And, in the tutorial MICROSOFT SOUND INPUT MAPPING is a selection option in the box of the recording device.  In my control PANEL, I double checked my USB audio device is active and functional. Why don't my box preferably says Microsoft Inpu acoustic mapping or something because my webcam is currently connected and it has audio, right? What to do to move forward in the implementation for MP3 at this rate?

    Hello

    According to the audacity of the site audio manufacturer is not compatible with windows vista however, there is a beta version, the customer may install follow the link below:

    http://Audacity.sourceforge.NET/Download/Windows

    I hope this helps.

  • PersistentStore, selectively loading records in memory possible?

    Hello

    I need to store images on the disk, I tried to use RMS but to see that the authorized maximum disk space is 64 KB.

    So now, I'm trying to store these images using the RIM API "PersistentStore." I'm trying to use it as a database because I can't store all images in memory at a time. I want to leave a few images on the disc, draw some in memory when needed.

    The example in the docs show an example where a vector is created, restaurant names (strings) are added to this vector, the vector is committed to the persistent store for you. I don't know if it helps me well because it implies that the store everything is kept in memory in the vector. I want to selectively load the images, not all those that I have stored on the disk.

    Is this possible? I read wrong?

    With the RMS system you could open the store and browse at least disc records before choosing to load in memory.

    That's what I read:

    http://NA.BlackBerry.com/eng/deliverables/647/BlackBerry_Java_Development_Environment_Development_Gu...

    Thank you

    Your application can use the FileConnections API and can have settings where the user can select the destination for the saved files.

    You can check by program this memory card and offer to record on SD card.

    If there is no present SD card - save the files to the internal memory, but keep an eye on the free internal memory volume.

  • To select adjacent records of same amount

    Oracle Version = Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production

    Hi gurus

    Yet once again, I need your help, I have the following data samples:

    Sample data:

    AS WITH a reference

    (

    SELECT 100 c_id,

    TO_DATE (November 1, 2006 ', 'dd-mm-yyyy') Eff_dt,.

    TO_DATE (October 31, 2008 ', 'dd-mm-yyyy') Ter_dt,.

    TN 55

    OF the double

    UNION ALL

    SELECT 100 c_id,

    TO_DATE (November 1, 2008 ', 'dd-mm-yyyy') Eff_dt,.

    TO_DATE (December 31, 2015 ', 'dd-mm-yyyy') Ter_dt,.

    55

    OF the double

    UNION ALL

    SELECT 200 c_id,

    TO_DATE (November 1, 2006 ', 'dd-mm-yyyy') Eff_dt,.

    TO_DATE (October 31, 2008 ', 'dd-mm-yyyy') Ter_dt,.

    60

    OF the double

    UNION ALL

    SELECT 200 c_id,

    TO_DATE (November 1, 2008 ', 'dd-mm-yyyy') Eff_dt,.

    TO_DATE (December 31, 2015 ', 'dd-mm-yyyy') Ter_dt,.

    75

    OF the double

    UNION ALL

    SELECT 200 c_id,

    TO_DATE (November 2, 2008 ', 'dd-mm-yyyy') Eff_dt,.

    TO_DATE (December 31, 2015 ', 'dd-mm-yyyy') Ter_dt,.

    60

    OF the double

    )

    SELECT * REFERENCE

    order by 1, 2;

    The query result

    C_ID, EFF_DT, TER_DT, TN

    100 1 NOVEMBER 06 31 OCTOBER 08 55

    100 1 NOVEMBER 08 TO 31 DECEMBER 15 55

    200 1ST NOVEMBER 06 31 OCTOBER 08 60

    200 1ST NOVEMBER 08 TO 31 DECEMBER 15 75

    200 2 NOVEMBER 08 TO 31 DECEMBER 15 60

    Required result

    100 1 NOVEMBER 06 31 OCTOBER 08 55

    100 1 NOVEMBER 08 TO 31 DECEMBER 15 55

    I need to select contagious AMT against C_ID,

    If you see examples of data, then you can see that the AMT 55 is contagious against C_ID = 100.

    If you see the same date, then you can see that the AMT 65 is not contagious against C_ID = 200, there is a record that has AMT = 75.

    order by should be EFF_DT. Thanks in advance

    Concerning

    Shu

    Hi, Shu,

    979596 wrote:

    Hi Frank

    Thanks for the reply, but when I added a record more against c_id = 200 then I get a wrong result, see below:

    Examples of data

    AS WITH a reference
    (
    SELECT 100 c_id,
    TO_DATE (November 1, 2006 ', 'dd-mm-yyyy') Eff_dt,.
    TO_DATE (October 31, 2008 ', 'dd-mm-yyyy') Ter_dt,.
    TN 55
    OF the double
    UNION ALL
    SELECT 100 c_id,
    TO_DATE (November 1, 2008 ', 'dd-mm-yyyy') Eff_dt,.
    TO_DATE (December 31, 2015 ', 'dd-mm-yyyy') Ter_dt,.
    55
    OF the double
    UNION ALL


    SELECT 200 c_id,
    TO_DATE (November 1, 2006 ', 'dd-mm-yyyy') Eff_dt,.
    TO_DATE (October 31, 2008 ', 'dd-mm-yyyy') Ter_dt,.
    60
    OF the double
    UNION ALL
    SELECT 200 c_id,
    TO_DATE (November 1, 2008 ', 'dd-mm-yyyy') Eff_dt,.
    TO_DATE (December 31, 2015 ', 'dd-mm-yyyy') Ter_dt,.
    75
    OF the double
    UNION ALL
    SELECT 200 c_id,
    TO_DATE (November 2, 2008 ', 'dd-mm-yyyy') Eff_dt,.
    TO_DATE (December 31, 2015 ', 'dd-mm-yyyy') Ter_dt,.
    60 DOUBLE
    UNION ALL
    SELECT 200 c_id,
    TO_DATE (November 3, 2008 ', 'dd-mm-yyyy') Eff_dt,.
    TO_DATE (December 31, 2015 ', 'dd-mm-yyyy') Ter_dt,.
    60
    OF the double
    )
    SELECT d.
    -COUNT (DISTINCT amt) over (PARTITION BY c_id) AS amt_cnt

    REFERENCE d
    order by 1, 2
    ;

    The query result

    100 1 NOVEMBER 06 31 OCTOBER 08 55

    100 1 NOVEMBER 08 TO 31 DECEMBER 15 55

    200 1ST NOVEMBER 06 31 OCTOBER 08 60

    200 1ST NOVEMBER 08 TO 31 DECEMBER 15 75

    200 2 NOVEMBER 08 TO 31 DECEMBER 15 60

    200 3 NOVEMBER 08 TO 31 DECEMBER 15 60

    Result of your request provided without filtering on amt_cnt

    100 1 NOVEMBER 06 31 OCTOBER 08-55-1

    100 1 NOVEMBER 08 TO 31 DECEMBER 15 55 1

    200 1ST NOVEMBER 06 31 OCTOBER 08 60 2

    200 1ST NOVEMBER 08 TO 31 DECEMBER 15 75 2

    200 2 NOVEMBER 08 TO 31 DECEMBER 15 60 2

    200 3 NOVEMBER 08 TO 31 DECEMBER 15 60 2

    ...

    When I run the query I posted earlier, with new data from the sample, I get no output with c_id = 200 lines.

    Power required

    100 1 NOVEMBER 06 31 OCTOBER 08-55-1

    100 1 NOVEMBER 08 TO 31 DECEMBER 15 55 1

    200 2 NOVEMBER 08 TO 31 DECEMBER 15 60 2

    200 3 NOVEMBER 08 TO 31 DECEMBER 15 60 2

    Maybe you want something like this:

    WITH got_neighbors AS

    (

    SELECT c_id, eff_dt, ter_dt, TN

    LAG (amt) over (PARTITION BY c_id

    ORDER BY eff_dt

    ) AS prev_amt

    Advance (amt) OVER (PARTITION BY c_id

    ORDER BY eff_dt

    ) AS next_amt

    REFERENCE

    )

    SELECT c_id, eff_dt, ter_dt, TN

    OF got_neighbors

    WHERE the amt IN (prev_amt, next_amt)

    ORDER BY c_id, eff_dt

    ;

    But I'm still guessing only to your needs.

    Specifically, I guess you want to see only those rows where TN is the same as the previous amt or amt next of the same c_id, where "previous" and "next" means in order of eff_dt.  However, if this is your requirement, so I do not understand why you did not say a word about eff_dt in your explanation, since eff_dt plays an important role in this problem.

  • Re: Error on select multiple records

    I need the script below to select a single record by person_id. But when I run it, I have several recordings by same person_id you I used separate in the Charly.

    As you can see below from the result of the query, the person_ids (21934 and 20102) appear twice.

    What I want is only one record a.person_id.

    Any guidance?



    select a.person_id, c.org_name, a.person_type, c.org_code, a.first_name, a.last_name, d.position_title, b.email_address
    from person a, person_emails b, organization c, position_titles d, positions e
    where a.person_id = b.person_id and a.employee_status = 'A' and a.organization_code = c.org_code and a.person_type = 'AMER HIRE' and a.organization_code = e.org_code  and d.position_title_number = e.position_title_number
    order by c.org_name
    ;
    20102 AFRICA Benin AMER HIRE 351801 Robert Tallman EXPERT r
    21934 AFRICA Benin AMER RENTAL 351801 Keith Howard COUNTRY DIRECTOR
    16440 AFRICA Benin AMER HIRE 351801 Jen Norinee EXPERT [email protected]
    20102 AFRICA Benin AMER HIRE 351801 Robert Tallman APCD/RURAL DEVELOPMENT rfrie
    21934 AFRICA Benin AMER RENTAL 351801 John Doe APCD and RURAL DEVELOPMENT
    21934 AFRICA Benin AMER RENTAL 351801 John Doe APCD/PROGRAMMING & TRAINING
    21934 AFRICA Benin AMER RENTAL 351801 John Doe k EXPERT

    You can try this and simply choose the title column that works for you, but for the first or the last title, you will need to fill in the correct sort order for this question:

     SELECT a.person_id
          , c.org_name
          , a.person_type
          , c.org_code
          , a.first_name
          , a.last_name
          , max(d.position_title) max_title
          , min(d.position_title) min_title
          , max(d.position_title)
              keep (dense_rank first order by some_column) first_title
          , max(d.position_title)
              keep (dense_rank last order by some_column) last_title
          , b.email_address
       FROM person a
          , person_emails b
          , organization c
          , position_titles d
          , positions e
      WHERE a.person_id             = b.person_id
        AND a.employee_status       = 'A'
        AND a.organization_code     = c.org_code
        AND a.person_type           = 'AMER HIRE'
        AND a.organization_code     = e.org_code
        AND d.position_title_number = e.position_title_number
      GROUP BY a.person_id
          , c.org_name
          , a.person_type
          , c.org_code
          , a.first_name
          , a.last_name
          , b.email_address
      ORDER BY c.org_name ;
    

    Moreover, in the future try formatting your code is readable with out having to scroll from left to right so.

    Published by: Sentinel on June 4, 2013 13:36

  • Select the records from the first n distinct values of column

    I need to write a query in plsql to select records for the first 3 values distinct from a single column (example below, ID) and all lines for the next 3 distinct values of column and so on until the end of the number of distinct values in a column.
    for example:
    Age of name ID
    1 abc 10
    1 def 20
    2 IA 10
    2 20 JKL
    2 mno 60
    3 10 pqr
    4 the RST 10
    4 10 TÜV
    5 vwx 10
    6 10 XYZ
    hij 6 10
    7 lmn 10
    .
    .
    .
    so now... (up to a few County)
    Result must be
    1 the application should result->
    Age of name ID
    1 abc 10
    1 def 20
    2 IA 10
    2 20 JKL
    2 mno 60
    3 10 pqr

    Query 2 should lead to->
    4 the RST 10
    4 10 TÜV
    5 vwx 10
    6 10 XYZ
    hij 6 10

    Query 3 should lead to->
    7 lmn 10
    .
    .
    9... ..
    so now...
    How to write a query for this inside a loop.

    Hello

    Thus, a panel will consist of the lowest id value, the 2nd lowest and the 3rd lower, reggardless of how many lines is involved. The next group will include the 4th lowest id, the 5th lowest and the 6th lowest. To do that, you must assign the numbers 1, 2, 3, 4, 5, 6,... for the rows in order by id, with all lines with the same id, getting the same number and without jumping all the numbers.
    This sounds like a job for the analytical DENSE_RANK function:

    WITH     got_grp_id     AS
    (
         SELECT     id, name, age
         ,     CEIL ( DENSE_RANK () OVER (ORDER BY id)
                   / 3
                   )          AS grp_id
         FROM     table_x
    )
    SELECT     id, name, age
    FROM     got_grp_id
    WHERE     id     = 1     -- or whatever number you want
    ;
    

    If you would care to post CREATE TABLE and INSERT statements for your sample data, then I could test it.
    See the FAQ forum {message identifier: = 9360002}

  • Selection of records based on the flag

    Hi all

    I have records as follows:

    Program name Effective_Date Valid_Flag
    N 10/02/2012 ABCD
    N 14/02/2012 ABCD
    ABCD 20/02/2012 Y
    N 01/03/2012 ABCD
    N 10/03/2012 ABCD
    ABCD 14/03/2012 Y
    N 25/03/2012 ABCD
    N 26/03/2012 ABCD
    N 27/03/2012 ABCD
    N 28/03/2012 ABCD
    N 29/03/2012 ABCD
    ABCD 25/04/2012 Y



    I have to write a select statement to keep the first record and then only pull records when the Valid_Flag has changed. The result set should be as below.

    Program name Effective_Date Valid_Flag
    ABCD 10/02/2012 N - I kept the first record
    20/02/2012 ABCD is - Valid_Flag chages to a Y for the first time and so on.
    N 01/03/2012 ABCD
    ABCD 14/03/2012 Y
    N 25/03/2012 ABCD
    ABCD 25/04/2012 Y

    If there is no change in the flag, I don't have to draw from this record. Please help with suggestions of SQL. Thanks for your time and your help.

    ssk1974 wrote:
    Hi all

    I have records as follows:

    Program name Effective_Date Valid_Flag
    N 10/02/2012 ABCD
    N 14/02/2012 ABCD
    ABCD 20/02/2012 Y
    N 01/03/2012 ABCD
    N 10/03/2012 ABCD
    ABCD 14/03/2012 Y
    N 25/03/2012 ABCD
    N 26/03/2012 ABCD
    N 27/03/2012 ABCD
    N 28/03/2012 ABCD
    N 29/03/2012 ABCD
    ABCD 25/04/2012 Y

    I have to write a select statement to keep the first record and then only pull records when the Valid_Flag has changed. The result set should be as below.

    Program name Effective_Date Valid_Flag
    ABCD 10/02/2012 N - I kept the first record
    20/02/2012 ABCD is - Valid_Flag chages to a Y for the first time and so on.
    N 01/03/2012 ABCD
    ABCD 14/03/2012 Y
    N 25/03/2012 ABCD
    ABCD 25/04/2012 Y

    If there is no change in the flag, I don't have to draw from this record. Please help with suggestions of SQL. Thanks for your time and your help.

    In the future, it would be nice if you could provide the sample data as below, I created.

    ME_XE?with data as
      2  (
      3     select 'ABCD' as col1, to_date('2/10/2012', 'mm/dd/yyyy')       as col2, 'N' as col3    from dual union all
      4     select 'ABCD' as col1, to_date('2/14/2012', 'mm/dd/yyyy')       as col2, 'N' as col3    from dual union all
      5     select 'ABCD' as col1, to_date('2/20/2012', 'mm/dd/yyyy')       as col2, 'Y' as col3    from dual union all
      6     select 'ABCD' as col1, to_date('3/01/2012', 'mm/dd/yyyy')       as col2, 'N' as col3    from dual union all
      7     select 'ABCD' as col1, to_date('3/10/2012', 'mm/dd/yyyy')       as col2, 'N' as col3    from dual union all
      8     select 'ABCD' as col1, to_date('3/14/2012', 'mm/dd/yyyy')       as col2, 'Y' as col3    from dual union all
      9     select 'ABCD' as col1, to_date('3/25/2012', 'mm/dd/yyyy')       as col2, 'N' as col3    from dual union all
     10     select 'ABCD' as col1, to_date('3/26/2012', 'mm/dd/yyyy')       as col2, 'N' as col3    from dual union all
     11     select 'ABCD' as col1, to_date('3/27/2012', 'mm/dd/yyyy')       as col2, 'N' as col3    from dual union all
     12     select 'ABCD' as col1, to_date('3/28/2012', 'mm/dd/yyyy')       as col2, 'N' as col3    from dual union all
     13     select 'ABCD' as col1, to_date('3/29/2012', 'mm/dd/yyyy')       as col2, 'N' as col3    from dual union all
     14     select 'ABCD' as col1, to_date('4/25/2012', 'mm/dd/yyyy')       as col2, 'Y' as col3    from dual
     15  )
     16  select *
     17  from
     18  (
     19     select
     20             col1, col2, col3,
     21             lag(col3) over (partition by col1 order by col2 asc) as last_flag
     22     from data
     23  )
     24  where last_flag    != col3
     25  or    last_flag    is null;
    
    COL1         COL2                       COL LAS
    ------------ -------------------------- --- ---
    ABCD         10-FEB-2012 12 00:00       N
    ABCD         20-FEB-2012 12 00:00       Y   N
    ABCD         01-MAR-2012 12 00:00       N   Y
    ABCD         14-MAR-2012 12 00:00       Y   N
    ABCD         25-MAR-2012 12 00:00       N   Y
    ABCD         25-APR-2012 12 00:00       Y   N
    
    6 rows selected.
    
    Elapsed: 00:00:00.08
    ME_XE?
    

    See you soon,.

  • How to select priority records

    Hi gurus,

    Here's the scenario of my problem. Records can be present/absent both in the table as follows.
    ELEMENT ID            ELEMENT DETAILS                    SOURCE  
    
    167               Some Details from S1-1          S1
    167               Some Details from S1-2          S1
    167               Some Details from S1-3          S1
    
    
    167               Some Details from S2-1          S2
    167               Some Details from S2-2          S2
    167               Some Details from S2-3          S2
    
    167               Some Details from S3-1          S3
    167               Some Details from S3-2          S3
    167               Some Details from S3-3          S3
    
                    OR records can be present as follows
    
    ELEMENT ID            ELEMENT DETAILS                    SOURCE  
    
    
    167               Some Details from S2-1          S2
    167               Some Details from S2-2          S2
    167               Some Details from S2-3          S2
    
    167               Some Details from S3-1          S3
    167               Some Details from S3-2          S3
    167               Some Details from S3-3          S3
    
                 OR  records can be present as follows
    
    ELEMENT ID            ELEMENT DETAILS                    SOURCE  
    
    167               Some Details from S1-1          S1
    167               Some Details from S1-2          S1
    167               Some Details from S1-3          S1
    
    
    
    167               Some Details from S3-1          S3
    167               Some Details from S3-2          S3
    167               Some Details from S3-3          S3
    
    and so on ...
    The result I want

    If all the RECORDS in sources (S1, S2, S3) are present and to SELECT only data source S1
    IF S2 and S3 RECORDS present and then SELECT only data S2.
    IF S3 RECORDS present data and then SELECT S3
    IF S1 and S3 RECORDS present data only SELECT S1
    IF S1 and S2 RECORDS then present S1 only SELECT data

    for example, S1 is on the highest priority, as appropriate and then S2 and S3 last.

    How to write a select based on above logic.

    Structure table data and the sample are less than
    create table element_priority(element_id number,element_details varchar2(100),source varchar2(100) )      
           
    insert into element_priority
    select * from (
    WITH T1 AS(
       SELECT    167, 'Some Details from S1-1',  'S1' from dual
       union
       SELECT    167, 'Some  Details from S1-2',  'S1' from dual
       union
       SELECT    167, 'Some Details from S1-3',  'S1' from dual
       union
       SELECT    167, 'Some Details from S2-1',   'S2' from dual
       union
       SELECT    167, 'Some Details from S2-2',   'S2' from dual
       union
       SELECT    167, 'Some Details from S2-3',   'S2' from dual
       union
        SELECT    167, 'Some Details from S3-1',   'S3' from dual
       union
       SELECT    167, 'Some Details from S3-2',   'S3' from dual
       union
       SELECT    167, 'Some Details from S3-3',   'S3' from dual
       )
       select * from   t1
    )
    Any help would be very appreciated

    Thanks in advance

    Use an analytic RANK(), DENSE_RANK() as ROW_NUMBER() according to what is required - perhaps DENSE_RANK or RANK what you have said and the possibility of having several #1 rankings in the same partition.

    Not sure if the precise logic is clear, but something like this:

    SQL> WITH T1(element_id, element_details, source) AS(
      2     SELECT    167, 'Some Details from S1-1',  'S1' from dual
      3     union
      4     SELECT    167, 'Some  Details from S1-2',  'S1' from dual
      5     union
      6     SELECT    167, 'Some Details from S1-3',  'S1' from dual
      7     union
      8     SELECT    167, 'Some Details from S2-1',   'S2' from dual
      9     union
     10     SELECT    167, 'Some Details from S2-2',   'S2' from dual
     11     union
     12     SELECT    167, 'Some Details from S2-3',   'S2' from dual
     13     union
     14      SELECT    167, 'Some Details from S3-1',   'S3' from dual
     15     union
     16     SELECT    167, 'Some Details from S3-2',   'S3' from dual
     17     union
     18     SELECT    167, 'Some Details from S3-3',   'S3' from dual
     19     )
     20  select element_id
     21  ,      element_details
     22  ,      source
     23  from   (select element_id
     24          ,      element_details
     25          ,      source
     26          ,      dense_rank() over (partition by element_id
     27                                    order by decode(source, 'S1',1,'S2',2,'S3',3)) rn            
    
     28          from   t1)
     29  where  rn = 1;
    
    ELEMENT_ID ELEMENT_DETAILS         SO
    ---------- ----------------------- --
           167 Some  Details from S1-2 S1
           167 Some Details from S1-1  S1
           167 Some Details from S1-3  S1
    
  • Select only records where the column values are not all equal to zero

    Hi everyone, it seems so easy, but it has left me speechless on the research in a way that is clean, easy to achieve. I know when someone replies, I'm going to kick me. So, let's assume this is what I have:
    with mytable as (
    select 'Type 1' as itemtype, 'JAN' as monthname, 0 as theval from dual union all
    select 'Type 1' as itemtype, 'FEB' as monthname, 1 as theval from dual union all
    select 'Type 1' as itemtype, 'MAR' as monthname, 5 as theval from dual union all
    select 'Type 1' as itemtype, 'APR' as monthname, 1 as theval from dual union all
    select 'Type 1' as itemtype, 'MAY' as monthname, 4 as theval from dual union all
    select 'Type 1' as itemtype, 'JUL' as monthname, 0 as theval from dual union all
    select 'Type 1' as itemtype, 'AUG' as monthname, 0 as theval from dual union all
    select 'Type 1' as itemtype, 'SEP' as monthname, 1 as theval from dual union all
    select 'Type 1' as itemtype, 'OCT' as monthname, 7 as theval from dual union all
    select 'Type 1' as itemtype, 'NOV' as monthname, 1 as theval from dual union all
    select 'Type 1' as itemtype, 'DEC' as monthname, 2 as theval from dual union all
    
    select 'Type 2' as itemtype, 'JAN' as monthname, 0 as theval from dual union all
    select 'Type 2' as itemtype, 'FEB' as monthname, 0 as theval from dual union all
    select 'Type 2' as itemtype, 'MAR' as monthname, 0 as theval from dual union all
    select 'Type 2' as itemtype, 'APR' as monthname, 0 as theval from dual union all
    select 'Type 2' as itemtype, 'MAY' as monthname, 0 as theval from dual union all
    select 'Type 2' as itemtype, 'OCT' as monthname, 0 as theval from dual union all
    select 'Type 2' as itemtype, 'NOV' as monthname, 0 as theval from dual union all
    select 'Type 2' as itemtype, 'DEC' as monthname, 0 as theval from dual
    )
    select
      itemtype,
      sum (case monthname when 'JAN' then theval else 0 end) as JAN,
      sum (case monthname when 'FEB' then theval else 0 end) as FEB,
      sum (case monthname when 'MAR' then theval else 0 end) as MAR,
      sum (case monthname when 'APR' then theval else 0 end) as APR,
      sum (case monthname when 'MAY' then theval else 0 end) as MAY,
      sum (case monthname when 'JUN' then theval else 0 end) as JUN,
      sum (case monthname when 'JUL' then theval else 0 end) as JUL,
      sum (case monthname when 'AUG' then theval else 0 end) as AUG,
      sum (case monthname when 'SEP' then theval else 0 end) as SEP,
      sum (case monthname when 'OCT' then theval else 0 end) as OCT,
      sum (case monthname when 'NOV' then theval else 0 end) as NOV,
      sum (case monthname when 'DEC' then theval else 0 end) as DEC
    from mytable
    group by itemtype
    order by itemtype
    I need an external application around it or something which will select only 'Type 1'... that is, if all months are each equal to zero, do not include the record in the result set.

    In summary to get a total of zero is not an option, because I could have-15 and + 15 in different columns, in which case, the recording should be displayed.

    Something as simple as... 'not the case (oct = 0 and 0 nov and dec = 0...) at the end is all it seems to me necessary. I thought to add a case for each column clause, but that seems not very effective. Ideas?

    Thanks in advance!
    Mark

    Edit... I know not what follows will work using the MINUS operator, but my actual query is really huge, and I don't want to have to write it twice...
    {code}
    Select
    ItemType,
    sum (case monthname when "JAN" then Val else 0 end) such as JAN,.
    sum (case when monthname 'FEB', then Val 0 otherwise end) by Feb.
    sum (case when monthname 'MAR', then Val 0 otherwise end) like MARS,
    sum (case monthname when "APR" then Val else 0 end) as APR.
    sum (case when monthname 'MAY', then Val else 0 end) either.
    sum (case when monthname "JUN", then Val 0 otherwise end) as JUN.
    sum (case monthname when "JUL" then Val else 0 end) as JUL,.
    sum (case monthname when "AUG" then Val else 0 end) as AUG.
    sum (case monthname when "MS" then Val else 0 end) as MS.
    sum (case monthname when "OCTS" then Val else 0 end) OCT.
    sum (case monthname when "NOV" then Val else 0 end) as NOV.
    sum (case monthname when 'DEC' then Val else 0 end) as DEC
    FROM MyTable
    Group of itemtype

    less

    Select
    ItemType,
    Jan, Feb, mar, Apr, may, June, July, August, Sept, oct, nov, dec
    de)
    Select
    ItemType,
    sum (case monthname when "JAN" then Val else 0 end) such as JAN,.
    sum (case when monthname 'FEB', then Val 0 otherwise end) by Feb.
    sum (case when monthname 'MAR', then Val 0 otherwise end) like MARS,
    sum (case monthname when "APR" then Val else 0 end) as APR.
    sum (case when monthname 'MAY', then Val else 0 end) either.
    sum (case when monthname "JUN", then Val 0 otherwise end) as JUN.
    sum (case monthname when "JUL" then Val else 0 end) as JUL,.
    sum (case monthname when "AUG" then Val else 0 end) as AUG.
    sum (case monthname when "MS" then Val else 0 end) as MS.
    sum (case monthname when "OCTS" then Val else 0 end) OCT.
    sum (case monthname when "NOV" then Val else 0 end) as NOV.
    sum (case monthname when 'DEC' then Val else 0 end) as DEC
    FROM MyTable
    Group of itemtype
    )
    where (oct = 0 & nov = 0 and dec = 0 and jan = 0 and 0 = Feb and mar = 0
    apr = 0 and may = 0 and = 0 jun and Jul = 0 and aug = 0 and Ms = 0
    )
    order of itemtype
    {code}

    Change again... OK, I guess that I am answering my own question here, but I think that by using a WITH to write the main request once clause and then selecting * twice using the MINUS operator between where the second query is where (oct = 0, etc.) is what I need. If anyone has better suggestions, please let me know! Here's the logic of nickname for what I come up with to date...

    {code}
    WITH mainquery as (select all)
    Select * from mainquery
    less
    Select * from mainquery where (oct = 0, nov = 0, etc...)
    {code}

    Thanks again!
    Mark

    Published by: user455268 on March 1, 2012 19:13

    Published by: user455268 on March 1, 2012 19:16

    Hello

    You can do it with a HAVING clause:

    select
      itemtype,
      sum (case monthname when 'JAN' then theval else 0 end) as JAN,
      sum (case monthname when 'FEB' then theval else 0 end) as FEB,
      sum (case monthname when 'MAR' then theval else 0 end) as MAR,
      sum (case monthname when 'APR' then theval else 0 end) as APR,
      sum (case monthname when 'MAY' then theval else 0 end) as MAY,
      sum (case monthname when 'JUN' then theval else 0 end) as JUN,
      sum (case monthname when 'JUL' then theval else 0 end) as JUL,
      sum (case monthname when 'AUG' then theval else 0 end) as AUG,
      sum (case monthname when 'SEP' then theval else 0 end) as SEP,
      sum (case monthname when 'OCT' then theval else 0 end) as OCT,
      sum (case monthname when 'NOV' then theval else 0 end) as NOV,
      sum (case monthname when 'DEC' then theval else 0 end) as DEC
    from mytable
    group by itemtype
    HAVING      MIN (theval)     != 0
    OR      MAX (theval)     != 0
    order by itemtype
    ;
    

    If the values are all 0, then the MIN and MAX will be 0.
    If the MIN or MAX is not 0, the values are all 0.

    This assumes that the combination (itemtype, monthname) is unique, because it is in your sample data.
    If this is not the case, start with a subquery that GROUPs BY itemtype, monthname, so that when you get to the main request, this combination will be unique.

  • Selection of records that are greater than the current week or

    Hi I have a table with the table structure

    CREATE TABLE OMPPRODUCTION
    (
    LOCATIONID VARCHAR2 (200 BYTE) NOT NULL,
    IPC VARCHAR2 (200 BYTE) NOT NULL,
    PRODUCTIONWEEK VARCHAR2 (200 BYTE) NOT NULL,
    QUANTITY VARCHAR2 (2000 BYTE),
    PRODUCTIONCODE VARCHAR2 (2000 BYTE),
    MOULDQUANTITY VARCHAR2 (2000 BYTE),
    VARCHAR2 (2000 BYTE) SOURCE,
    VARCHAR2 (2000 BYTE) APPLICATION,
    COMMENTS VARCHAR2 (2000 BYTE),
    DATE OF TLM,
    ADSTAT CHAR (1 BYTE),
    SID NUMBER (10, 0),
    SECURITYLEVEL VARCHAR2 (100 BYTE),
    ENABLE CONSTRAINT PRIMARY KEY (LOCATIONID, CPI, PRODUCTIONWEEK) OMPPRODUCTION_PK
    )

    He has field PRODUCTIONWEEK that is to be given YYYYMMDD.

    I want to select records that are starting the week underway (Monday as departure day).

    for example, the date is 20120210 so I would choose the lines including the date more or equal to 20120206.

    Can someone guide me how it is possible?

    Published by: MaheshGx on 6 February 2012 16:16

    MaheshGx wrote:
    Select * from OMPPRODUCTION where to_number (to_char (to_date (productionweek, 'yyyymmdd'), 'WW')) > = to_number (to_char (sysdate, "WW"))

    Wow, why so complicated?

    You work with dates, so:

    (a) why the hell you store dates in a column VARCHAR2? (and worse yet, why is 200 bytes of length)? Store dates as the DATE. The optimizer based on CSSTidy will thank you. As well, you know, you won't be wasting space.
    (b) compare with the dates, not dates-converted dates - dates-converted-to-number numbers. Why do extra work when you have not to?

    Since you're after weeks from Monday, I'd go for the format mask "IW", since it is fixed and will always return the Monday of the current week ("WW" could return Sunday or Monday, depending on what are your NLS settings.) I'd rather have my labour code for those who executes it, regardless of their NLS settings).

    So, given the fact that your column is not the DATE data type, it would be more effective for you;

    select *
    from   ompproduction
    where  trunc(to_date(productionweek,'yyyymmdd'), 'iw') >= trunc(sysdate, 'iw');
    

    If you have an index on productionweek that you need help in this query, then I suggest to convert it to a basic index function.

Maybe you are looking for