Subquery scalar to select max

Hi all

Oracle Version
11.2.0.1.0


I need to write a query update one table based on the following criteria:
create table trades (tid number, descp varchar2(20));

create table trade_descp (tid number, aud_desc varchar2(20), c_date date)


insert into trades
values
(1,NULL)

insert into trades
values
(3,NULL)

insert into trades
values
(4,NULL)

insert into trade_descp values
(1,'abdc(M)','1-Jan-2012')

insert into trade_descp values
(1,'abdc(M)','1-Jan-2013')

insert into trade_descp values
(1,'abdc(N)','1-Jan-2014')
The output I need is to update the table of trades with a description with the maximum date of trade_descp table based on a filter for example descp like "%M %.
There is an index on the column tid trade_descp table (with huge files).

Can this be achieved in direct SQL.


Thank you and best regards,
Nik

Nikhil Juneja wrote:
but that is a full table of trade_descp table scan. Can we make us of the index built on the TID column?

SQL> merge
  2    into trades a
  3    using (
  4           select  tid,
  5                   max(aud_desc) keep(dense_rank last order by c_date) descp
  6             from  trade_descp
  7             where aud_desc like '%M%'
  8             group by tid
  9          ) b
 10      on (
 11          b.tid = a.tid
 12         )
 13    when matched
 14      then update
 15              set a.descp = b.descp
 16  /

1 row merged.

SQL> select  *
  2    from  trades
  3  /

       TID DESCP
---------- --------------------
         1 abdc(M)
         3
         4

SQL> explain plan for
  2  merge
  3    into trades a
  4    using (
  5           select  tid,
  6                   max(aud_desc) keep(dense_rank last order by c_date) descp
  7             from  trade_descp
  8             where aud_desc like '%M%'
  9             group by tid
 10          ) b
 11      on (
 12          b.tid = a.tid
 13         )
 14    when matched
 15      then update
 16              set a.descp = b.descp
 17  /

Explained.

SQL> @?\rdbms\admin\utlxpls

PLAN_TABLE_OUTPUT
-----------------------------------------------------------------------------------------------------------------------------
Plan hash value: 1775522890

----------------------------------------------------------------------------------------------------
| Id  | Operation                       | Name             | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------------------------------
|   0 | MERGE STATEMENT                 |                  |     2 |    48 |     5  (20)| 00:00:01 |
|   1 |  MERGE                          | TRADES           |       |       |            |          |
|   2 |   VIEW                          |                  |       |       |            |          |
|   3 |    SORT GROUP BY                |                  |     2 |   142 |     5  (20)| 00:00:01 |
|   4 |     NESTED LOOPS                |                  |       |       |            |          |
|   5 |      NESTED LOOPS               |                  |     2 |   142 |     4   (0)| 00:00:01 |
|   6 |       TABLE ACCESS FULL         | TRADES           |     3 |   111 |     3   (0)| 00:00:01 |
|*  7 |       INDEX RANGE SCAN          | TRADE_DESCP_IDX1 |     3 |       |     0   (0)| 00:00:01 |
|*  8 |      TABLE ACCESS BY INDEX ROWID| TRADE_DESCP      |     1 |    34 |     1   (0)| 00:00:01 |
----------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   7 - access("TID"="A"."TID")
   8 - filter("AUD_DESC" IS NOT NULL AND "AUD_DESC" LIKE '%M%')

Note
-----
   - dynamic sampling used for this statement (level=2)

25 rows selected.

SQL> 

SY.

Tags: Database

Similar Questions

  • With the help of SELECT MAX (Substr (in a subquery to return specific lines

    Oracle v10

    Here is an example of a query and the output
    SELECT ID, SAMPLEID, COMPOUNDNAME, REQUISITION, SUBSTR(REQUISITION,2,4) FROM SEARCH PL1 WHERE SAMPLEID = 'IA 0005 0166';
    
    86907     IA 0005 0166     IA 0005     R2004:001160     2004
    98158     IA 0005 0166     IA 0005     R2005:000956     2005
    I try to return only the last line of data, in this case the line 2005.

    I tried
    SELECT ID, SAMPLEID, COMPOUNDNAME, REQUISITION, SUBSTR(REQUISITION,2,4) FROM SEARCH PL1 
    WHERE SAMPLEID = 'IA 0005 0166' AND
    REQUISITION IN 
    (SELECT MAX(SUBSTR(REQUISITION,2,4)) FROM SEARCH PL2 
    WHERE SUBSTR(PL2.REQUISITION,2,4) = SUBSTR(PL1.REQUISITION,2,4));
    But it returns no results. According to me, only missing me something simple.

    TIA

    You probably meant it?

    SELECT ID, SAMPLEID, COMPOUNDNAME, REQUISITION, SUBSTR(REQUISITION,2,4)
    FROM SEARCH PL1
    WHERE SAMPLEID = 'IA 0005 0166'
    AND SUBSTR(REQUISITION,2,4) = (
      SELECT MAX(SUBSTR(PL2.REQUISITION,2,4))
      FROM SEARCH PL2
      WHERE PL2.SAMPLE_ID = PL1.SAMPLE_ID
    );
    

    that could also be achieved with a single table access:

    SELECT id, sampleid, compoundname, requisition, sub_req
    FROM (
      SELECT id, sampleid, compoundname, requisition, substr(requisition,2,4) sub_req,
             row_number() over(order by substr(requisition,2,4) desc) rn
      FROM search PL1
      WHERE sampleid = 'IA 0005 0166'
    )
    WHERE rn = 1
    ;
    
  • Select Max (date) multiple records

    I'm having a problem getting the last value for several gauges.  Here's my query:

    SELECT parameter_id,

    TS_ID,

    value,

    Location_id,

    Date_Time

    Of

    MyTable

    JOIN IN-HOUSE

    mytable2

    WE

    TS_ID = ts_id

    WHERE

    TS_ID LIKE '% - rev.

    unit_id = ("pi")

    the value IS NOT NULL

    Location_id as "xxxx".

    Date_Time =

    (SELECT Max (date_time)

    My TABLE

    GROUP BY parameter_id)

    ;

    Hello

    A scalar subquery, such as the expression to the right of the sign =

    Date_Time = (SELECT...)

    must produce (at most) only 1 row.  If the subquery produces 2 or more lines, it will trigger an error.

    Given that you are using "GROUP BY parameter_id" in the subquery, it will produce a separate line of output for each distinct value of parameter_id.  You can use a correlated subquery at that time, that only looks like a parameter_id, or you can use a subquery IN, like this:

    WHERE (parameter_id, Date_Time) IN

    (

    SELECT parameter_id

    MAX (date_time)

    FROM MyTable

    GROUP BY parameter_id

    )

    I hope that answers your question.
    If not, post a small example data (CREATE TABLE and only relevant columns, INSERT statements) and also publish outcomes from these data.
    Explain, using specific examples, how you get these results from these data.
    Always say what version of Oracle you are using (for example, 11.2.0.2.0).

    See the FAQ forum: https://forums.oracle.com/message/9362002#9362002

  • Update statement Select MAX

    Hello guys, small head scratcher here (probably just my mind head)

    Summary of the issue: Updated between two tables, try to use the rank, will not work.

    I took a few of the fields of interest here: -.
    CREATE TABLE spell_tags (
          Spell_ID             varchar2(50) ,
          service_line_spell     varchar2(25) );
    CREATE TABLE ranked_spells(
         spell_ID varchar2(10) ,
         dominant_SSNDS varchar2(25) ,
         service_line varchar2(25) ,
         Rank varchar2(3) NOT NULL ) ;
    Samples: -.
    INSERT INTO RANKED_SPELLS ("SPELL_ID" ,"DOMINANT_SSNDS" ,"SERVICE_LINE" ,"RANK" ) VALUES ('100002' ,'08' ,'SD08o' ,'213' );
    INSERT INTO RANKED_SPELLS ("SPELL_ID" ,"DOMINANT_SSNDS" ,"SERVICE_LINE" ,"RANK" ) VALUES ('100002' ,'08' ,'SD08s' ,'210' );
    INSERT INTO RANKED_SPELLS ("SPELL_ID" ,"DOMINANT_SSNDS" ,"SERVICE_LINE" ,"RANK" ) VALUES ('100003' ,'08' ,'SD22m' ,'416' );
    INSERT INTO RANKED_SPELLS ("SPELL_ID" ,"DOMINANT_SSNDS" ,"SERVICE_LINE" ,"RANK" ) VALUES ('100003' ,'08' ,'SD23x' ,'207' );
    INSERT INTO SPELL_TAGS ("SPELL_ID" , "SERVICE_LINE_SPELL"  ) VALUES ('100002' ,'' );
    INSERT INTO SPELL_TAGS ("SPELL_ID" , "SERVICE_LINE_SPELL"  ) VALUES ('100003' ,'' );
    Data looks like this: -.
     Select * from spell_tags;
    
    SPELL_ID                                           SERVICE_LINE_SPELL
    -------------------------------------------------- -------------------------
    100002
    100003
    
    2 rows selected.
    
    
     Select * from ranked_spells;
    
    
    SPELL_ID   DOMINANT_SSNDS            SERVICE_LINE              RANK
    ---------- ------------------------- ------------------------- ---
    100002     08                        SD08o                     213
    100002     08                        SD08s                     210
    100003     08                        SD22m                     416
    100003     08                        SD23x                     207
    
    4 rows selected.
    Basically, I need to run and update the declaration (not plsql) to update the Spell_tags table service_line_spell field with the service_line of the ranked_spells table (lowest rank)

    Here are a few failed attempts, do not laugh ;)
    update spell_tags
    set service_line_spell = (select max(service_line) from ranked_spells
    where spell_tags.spell_id = ranked_spells.spell_ID
    group by service_line, rank
    having rank = min(rank))
    where spell_ID in (select distinct spell_ID from ranked_spells);
    
    ERROR at line 2:
    ORA-01427: single-row subquery returns more than one row
    
    
    update speccom.spell_tags
    set service_line_spell = (select b.service_line from ranked_spell b
    where spell_tags.spell_id = ranked_spells.spell_ID
    and ranked_spells.rank = min(ranked_spells.rank) group by service_line, rank)
    where exists
    (select spell_ID from ranked_spells
    where spell_ID in (select distinct spell_ID from ranked_spells);
    
    ERROR at line 4:
    ORA-00934: group function is not allowed here
    This is the result, I need: -.
     Select * from spell_tags;
    
    SPELL_ID                                           SERVICE_LINE_SPELL
    -------------------------------------------------- -------------------------
    100002                                             SD08s
    100003                                               SD23x
    Any ideas guys?

    Something like that?

    update spell_tags
    set service_line_spell = (select max(service_line) keep (dense_rank last order by rank desc)
                              from ranked_spells
                              where spell_tags.spell_id = ranked_spells.spell_ID
                              )
    where spell_ID in (select distinct spell_ID from ranked_spells);
    

    Published by: UW (Germany) on 16.08.2012 16:48 (changed min at the maximum, but it makes only a difference when there is same ranking values)

  • Subquery in the select clause and not "a group by expression" error.

    Hi all
    I hope someone out there can help me out with this one. I have a sql query that performs a subquery in the select case combined with an aggregate function and gives me a "not a group by expression.

    I created a simplified example
     SELECT COUNT(*)                     ,
      ai.invoice_num invoice_number      ,
      ai.description invoice_description ,
      (SELECT poh.po_header_id
           FROM po_headers poh ,
          po_distributions pod
          WHERE pod.po_distribution_id = aid.po_distribution_id
        AND pod.po_header_id           = poh.po_header_id
        ) po_number
         FROM ap_invoice_distributions aid ,
        ap_invoices ai
        WHERE ai.invoice_id = 1476932
      AND aid.project_id    = 8608   
      AND aid.task_id       = 462202  
      AND ai.invoice_id     = aid.invoice_id
     GROUP BY ai.invoice_num,
                    ai.description;
    I'm sure he expected me to add the po_number to the group by clause, but this does not work and gives the error "invalid identifier".

    Can someone suggest a way for a new concert the query so that I can add po_number to my education by clause.

    Kris

    You should try either:

    SELECT COUNT (*),
    AI.invoice_num invoice_number,
    have. Description invoice_description,
    (SELECT poh.po_header_id
    OF po_headers poh,.
    pod po_distributions
    WHERE pod.po_distribution_id = aid.po_distribution_id
    AND pod.po_header_id = poh.po_header_id
    ) po_number
    HELP ap_invoice_distributions.
    ap_invoices AI
    WHERE ai.invoice_id = 1476932
    AND aid.project_id = 8608
    AND aid.task_id = 462202
    AND ai.invoice_id = aid.invoice_id
    Ai.invoice_num GROUP,
    have. Description, aid.po_distribution_id;

    or

    SELECT COUNT (*),
    AI.invoice_num invoice_number,
    have. Description invoice_description,
    MAX ((SELECT poh.po_header_id
    OF po_headers poh,.
    pod po_distributions
    WHERE pod.po_distribution_id = aid.po_distribution_id
    AND pod.po_header_id = poh.po_header_id
    po_number))
    HELP ap_invoice_distributions.
    ap_invoices AI
    WHERE ai.invoice_id = 1476932
    AND aid.project_id = 8608
    AND aid.task_id = 462202
    AND ai.invoice_id = aid.invoice_id
    Ai.invoice_num GROUP,
    have. Description;

  • Select Max (Date) in two different tables...

    Dear all,

    I need the date of last update of two different tables, I mean max (date). We will update one table at a time. Updated once I need to take the last update.

    It can be either in table A table B.

    for example.

    Table A

    Date of the ID

    100 16/05/2014

    101 20/05/2014

    102, 22/05/2014

    Table B

    Date of the ID

    100 04/06/2014

    101, 26/05/2014

    102 21/05/2014

    I need the date of table B (101 26/05/2014) last updated date...

    Hello

    Another way, using much more GRAND:

    SELECT LARGER (max1, max2) x

    FROM (SELECT MAX (mydate) max1

    OF mytable_a

    )

    (SELECT MAX (myotherdate) max2

    OF mytable_b

    )

    ;

    Best regards

    Bruno Vroman.

  • Select Max (date) between multiple tables

    I need to retrieve a record from a Table in a set of similar tables with a common "date field". You can select the record where this "date field" value is greater between multiple tables.

    Here, any help is appreciated.  Thank you in advance.

    FOR EXAMPLE

    No. EMP is the primary key.

    Again, each table can have multiple records for EMP n ° 1

    TABLE1:

    FIRST NAME

    FAMILY NAME
    THE EMP NO.

    BASE SALARY

    DATE_FROM

    TABLE 2

    FIRST NAME

    FAMILY NAME
    THE EMP NO.

    SALARY GRADE

    DATE_FROM

    TABLE 3

    FIRST NAME

    FAMILY NAME
    THE EMP NO.

    COMPENSATION

    DATE_FROM

    Hello

    Said Knani, if you use the current design of the table, then here is a way to do what you want:

    WITH union_data AS

    (

    SELECT MAX (base_salary) AS sal FROM table1 UNION ALL

    SELECT MAX (grade_salary) table2 UNION ALL

    SELECT MAX (compensation) FROM table3

    )

    SELECT MAX (sal) AS max_sal

    Of union_data

    ;

  • SELECT MAX (FILE_VERSION)

    I put the following portion of the code in a WHERE clause:
               AND PCMS_CHDOC_ACTION_DESC_2.FILE_VERSION IN 
    
                      (SELECT MAX(FILE_VERSION) 
    
                         FROM PCMS_CHDOC_ACTION_DESC PCMS_CHDOC_ACTION_DESC_4
    
                       WHERE PCMS_CHDOC_ACTION_DESC_4.CH_UID = PCMS_CHDOC_DATA_2.CH_UID                                                                              AND PCMS_CHDOC_ACTION_DESC_4.CH_DOC_ID = PCMS_CHDOC_DATA_2.CH_DOC_ID)
    .. .but for records where the FILE_VERSION is null or doesn't retrieve any record.

    There is a way to write such can also retrieve records that are null?
    AND (PCMS_CHDOC_ACTION_DESC_2.FILE_VERSION IN
                      (SELECT MAX(FILE_VERSION)
                         FROM PCMS_CHDOC_ACTION_DESC PCMS_CHDOC_ACTION_DESC_4
                      WHERE PCMS_CHDOC_ACTION_DESC_4.CH_UID = PCMS_CHDOC_DATA_2.CH_UID
                                    AND PCMS_CHDOC_ACTION_DESC_4.CH_DOC_ID = PCMS_CHDOC_DATA_2.CH_DOC_ID
                                  ) OR PCMS_CHDOC_ACTION_DESC_2.FILE_VERSION IS NULL)
    

    or doesn't exist doesn't retrieve any record.
    

    What do you mean by that?
    * 009 *.

    Published by: 009 April 16, 2010 12:14 AM

  • Select max in a specific range only?

    Hello experts and pros of sql!

    I guess that I need your help on a problem I've been struggling with for hours now.

    I have the following query, which, in the final version will be written in the pl/sql code:
    SELECT
         CNT_GEBIET,
         CNT_GEBIET DISPLAY,
         CNT_GEBIET BUTTON,
         STR_NAME,
         decode(STR_ART_GEBIETE,'Vogelschutz','SPA','FFH','FFH','FFH und Vogelschutz','FFH & SPA') STR_ART_GEBIETE,
         STR_REG_KART_TEAMS,
         STR_BESCHREIBUNG,
         BOOL_ANZEIGEN,
         STR_FEDERFUEHRENDE,
         K.INT_VERFAHREN,
         STR_VERFAHREN,
         D.ST_BIOGEO,
         D.STR_GEBIET,
         E.STR_BIOGEO,
         E.INT_BIOGEO,
    case when to_char(min(L.DATE_GP_RT_END), 'YYYY') < to_char(sysdate, 'YYYY')  then 'red'
    else 'green' end as mxcolour,
    case when to_char(min(L.DATE_R_AT_END), 'YYYY') <= to_char(sysdate, 'YYYY') then 'green'
    when to_char(min(L.DATE_R_V_END), 'YYYY') > to_char(min(L.DATE_GP_V_END), 'YYYY') then 'red'
    else 'black' end as mxcolour_r_date,
       to_char(min(L.DATE_GP_AT_START), 'YYYY')  DATE_GP_AT_START,
       to_char(min(L.DATE_R_AT_END), 'YYYY')  DATE_R_AT_END,
       to_char(min(L.DATE_GP_V_START), 'YYYY')  DATE_GP_V_START,
       to_char(min(L.DATE_R_V_END), 'YYYY')  DATE_R_V_END,
       to_char(min(L.DATE_GP_RT_START), 'YYYY')  DATE_GP_RT_START,
       to_char(min(L.DATE_R_RT_END), 'YYYY')  DATE_R_RT_END,
       I.GEB,
       I.STR_REGBEZE,
       H.ALF,
       I.LNG_REG_KART_TEAMS,
    
       MAX(NVL(M.LNG_ARBEITSSCHRITT,21)) LNG_ARBEITSSCHRITT
    
    FROM VT_TBL_ARBEIT_ZU_GEBIET M
    RIGHT OUTER JOIN (
      VT_TBL_GEBIET K
      INNER JOIN VT_TBL_ART_GEBIETE B ON B.CNT_ART_GEBIETE = K.INT_ART_GEBIET
      INNER JOIN VT_TBL_FEDERFUEHRENDE C ON C.CNT_FEDERFUEHRENDE = K.LNG_FEDER
      INNER JOIN VT_TBL_GEBIET_ZU_BIOGEO D ON D.STR_GEBIET = K.CNT_GEBIET
      INNER JOIN VT_TBL_BIOGEO E ON D.ST_BIOGEO = E.INT_BIOGEO
      INNER JOIN VT_TBL_VERFAHREN F ON F.CNT_VERFAHREN = K.INT_VERFAHREN
      INNER JOIN VT_TBL_REG_KART_TEAMS G ON G.CNT_REG_KART_TEAMS = K.INT_REG_KART_TEAMS
      INNER JOIN VT_TBL_GEBIET_ZU_ALF H ON H.GEBIET = K.CNT_GEBIET
      INNER JOIN TBL_REGBEZE I ON I.GEB = K.CNT_GEBIET
          AND I.LNG_REG_KART_TEAMS = G.CNT_REG_KART_TEAMS
    ) ON M.LNG_GEBIET = K.CNT_GEBIET
    LEFT OUTER JOIN TBL_ARBEITSSCHRITTE_NEU A
      ON M.LNG_ARBEITSSCHRITT = A.CNT_ARBEITSSCHRITT
    left outer join vt_tbl_arbeit_crit_date l on l.lng_gebiet = k.cnt_gebiet
       where k.cnt_gebiet not like '%Test%' and nvl(m.lng_arbeitsschritt,21) not in (1,4,13,23,28,31,45,54,60,66,73,78) and nvl(l.lng_arbeitsschritt,1) = 1
    GROUP BY
        CNT_GEBIET,
        STR_NAME,
        STR_ART_GEBIETE,
        STR_REG_KART_TEAMS,
        LNG_REG_KART_TEAMS,
        H.ALF,
        STR_BESCHREIBUNG,
        BOOL_ANZEIGEN,
        STR_FEDERFUEHRENDE,
        D.ST_BIOGEO,
        D.STR_GEBIET,
        E.STR_BIOGEO,
        E.INT_BIOGEO,
        F.STR_VERFAHREN,
        K.INT_VERFAHREN,
        I.GEB,
        I.STR_REGBEZE,
        L.DATE_GP_AT_START,
        L.DATE_R_AT_END,
        L.DATE_GP_V_START,
        L.DATE_R_V_END,
        L.DATE_GP_RT_START,
        L.DATE_R_RT_END
    My problem is that I want to select MAX (M.LNG_ARBEITSSCHRITT) while the max value is supposed to be limited to a specific range.

    Indeed, the 1,4,13,23,28,31,45,46,54,60,66,73,78 values should not take into account.

    Can you please show me how to specify a range of values that can be used for the calculation of the max (m.lng_arbeitsschritt)?

    I appreciate your help and your entry!

    Thank you to have a look at this post!

    Kind regards

    SEB

    Try:

    max(case when M.LNG_ARBEITSSCHRITT not in (1,4,13,23,28,31,45,46,54,60,66,73,78) then M.LNG_ARBEITSSCHRITT end)
    
  • Select max (length) - how to display the length of a group MAX

    Hello

    I have a table with the name of DVD and names of files on the DVD.
    I would like to know how to change this query to get another column, MAX_LENGHT, the MAXIMUM length of the name of FILE to a DVD of return
    This doesn't work request
    select DVD, FILENAME, (SELECT max(length(FILENAME)) / 2 + 4 FROM TABLE) AS MAX_LENGHT from TABLE
    DESIRED RESULT
    DVD    FILENAME     MAX LENGHT
    DVD1     Alina     8
    DVD1     Aidan     8
    DVD1     Aiden     8
    DVD1     Akira     8
    DVD1     Alex     8
    DVD1     Alyssa     8
    DVD1     Arianna     8
    DVD1     Ashley     8
    DVD1     Ava     8
    DVD1     Benjamin8
    DVD1     Bianca     8
    DVD1     Blake     8
    DVD1     Brandon     8
    DVD1     Brayden     8
    DVD1     Brayden     8
    DVD1     Brianna     8
    DVD1     Brielle     8
    DVD1     Brooklyn8
    DVD2     Dakota     11
    DVD2     Dalia     11
    DVD2     Daniel     11
    DVD2     Dante     11
    DVD2     David     11
    DVD2     Diego     11
    DVD2     Dingbang11
    DVD2     Dominic     11
    DVD2     Dylan     11
    DVD2     Chase     11
    DVD2     Chloe     11
    DVD2     Christopher     11
    DVD2     Claire     11
    DVD2     Cole     11
    DVD2     Connor     11
    Thank you

    Roseline

    You can use the analytic version of the function max:

    SELECT  DVD
    ,       FILENAME
    ,       MAX(LENGTH(FILENAME)) OVER (PARTITION BY DVD) AS MAX_LENGTH
    FROM    TABLE
    
  • HELP! : SELECT &amp; MAX

    I had a few difficulties to do a sql query.

    Table 1: Master

    2 columns: name, Contact_ID
    Name1, contact_id_1
    name 2, contact_id_2
    name 3, contact_id_3

    ...

    Table 2: details
    2 columns: Version Contact_id, address,.
    contact_id_1, address_a, 1
    contact_id_1, address_b, 2
    contact_id_2, address_c, 1
    contact_id_2, address_d, 2
    contact_id_2, address_e, 3
    contact_id_3, address_f, 1
    ......

    Question I have:

    How can I make a query showing the list of names with the address with the latest version?

    Result: I'm looking:

    Name1, address_b
    name 2, address_e
    name 3, address_f
    .......

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

    Thank you very much for the help in advance!
    with master as
    (
      select 'name1' as name, 'contact_id_1' as contact_id from dual union all
      select 'name2' as name, 'contact_id_2' as contact_id from dual union all
      select 'name3' as name, 'contact_id_3' as contact_id from dual
    ),
    detail as
    (
      select 'contact_id_1' as contact_id, 'address_a' as address, 1 as version from dual union all
      select 'contact_id_1' as contact_id, 'address_b' as address, 2 as version from dual union all
      select 'contact_id_2' as contact_id, 'address_c' as address, 1 as version from dual union all
      select 'contact_id_2' as contact_id, 'address_d' as address, 2 as version from dual union all
      select 'contact_id_2' as contact_id, 'address_e' as address, 3 as version from dual union all
      select 'contact_id_3' as contact_id, 'address_f' as address, 1 as version from dual
    )
    --
    -- end of test data, query is below
    --
    select m.name,
           d.address
    from   master m,
           detail d
    where  m.contact_id = d.contact_id
    and    d.version = (select max(version) from detail d2 where d2.contact_id = d.contact_id)
    /
    
    NAME  ADDRESS
    ----- ---------
    name1 address_b
    name2 address_e
    name3 address_f 
    
    3 rows selected
    

    Published by: Cyn on December 17, 2009 16:39

  • SQL select max value in a group

    Hi all!

    Newbie question here... I'm a bit confused by how accomplish getting the maximum value for a group within a game when I have several tables going on results.

    I need to capture only the T2. BI_TASK_CD and MAX (T2. BI_WRKFLW_TASK_SEQ_NBR) for each unique "SO NBR.

    So, in this example below, I should finish with only 3 rows for re ' 2227510 ', ' 2211700', 2227515'


    I have:
    SELECT 
    T1.MSTR_SO_NBR AS "SO NBR",
    T1.BI_WRKFLW_TASK_SEQ_NBR,
    T1.BI_TASK_CD,
    T1.BI_EVENT_DT_TM,
    T1.BI_CRITICAL_TASK_SW,
    T2.BI_TASK_CD as "T2.BI_TASK_CD",
    T2.BI_WRKFLW_TASK_SEQ_NBR as "T2.BI_WRKFLW_TASK_SEQ_NBR",
    T2.BI_EVENT_DT_TM as "T2.BI_EVENT_DT_TM",
    T2.BI_CRITICAL_TASK_SW as "T2.BI_CRITICAL_TASK_SW"
    
    FROM
    (SELECT DISTINCT
      BI_SO_MASTER.BI_SO_NBR as "MSTR_SO_NBR",
      BI_SO_DET_VIEW_1.BI_SO_NBR,
      BI_WRKFLW_TASKS.BI_WRKFLW_TASK_SEQ_NBR,
      BI_WRKFLW_TASKS.BI_TASK_CD,
      BI_WRKFLW_TASKS.BI_EVENT_DT_TM,
      BI_WRKFLW_TASKS.BI_CRITICAL_TASK_SW
    FROM(XXX)
    ...
    ) T1
    
    LEFT OUTER JOIN
    
     (SELECT DISTINCT
           --BI_SO_MASTER.BI_SO_NBR,
           BI_SO_DET_VIEW_1.BI_SO_NBR,
           BI_WRKFLW_TASKS.BI_WRKFLW_TASK_SEQ_NBR,
           BI_WRKFLW_TASKS.BI_TASK_CD,
           BI_WRKFLW_TASKS.BI_EVENT_DT_TM,
           BI_WRKFLW_TASKS.BI_CRITICAL_TASK_SW 
     FROM(XXX)  
    ...
    ) T2
    
    ON 
    T1.BI_SO_NBR = T2.BI_SO_NBR 
    
    WHERE
    T2.BI_WRKFLW_TASK_SEQ_NBR < T1.BI_WRKFLW_TASK_SEQ_NBR
    AND T1.BI_SO_NBR IN ('2227510', '2211700', '2227515')
    
    ORDER BY 
    "SO NBR" ASC,
    T2.BI_WRKFLW_TASK_SEQ_NBR DESC
    Current result set:
    SO NBR  BI_WRKFLW_TASK_SEQ_NBR BI_TASK_CD BI_EVENT_DT_TM      BI_CRITICAL_TASK_SW T2.BI_TASK_CD T2.BI_WRKFLW_TASK_SEQ_NBR T2.BI_EVENT_DT_TM   T2.BI_CRITICAL_TASK_SW                                         
    ------- ---------------------- ---------- ------------------- ------------------- ------------- ------------------------- ------------------- ----------------------                                         
    2211700 21                     OPSCREW    2012-01-16 11:37:14 Y                   ENGWORVIPG    20                        2012-01-16 11:37:14 Y                                                              
    2211700 21                     OPSCREW    2012-01-16 11:37:14 Y                   SERVCOORD     19                        2012-01-16 11:37:14 Y                                                              
    2211700 21                     OPSCREW    2012-01-16 11:37:14 Y                   ENGWORVIPG    17                        2012-01-16 11:37:14 Y                                                              
    2211700 21                     OPSCREW    2012-01-16 11:37:14 Y                   ENGSTKASGN    16                        2012-01-16 11:37:14 Y                                                              
    2211700 21                     OPSCREW    2012-01-16 11:37:14 Y                   ENGNWO        13                        2012-01-16 11:37:14 Y                                                              
    2211700 21                     OPSCREW    2012-01-16 11:37:14 Y                   PAYCOLLECT    12                        2012-01-16 11:37:14 Y                                                              
    2211700 21                     OPSCREW    2012-01-16 11:37:14 Y                   PRESENTVAL    11                        2012-01-16 11:37:14 Y                                                              
    2211700 21                     OPSCREW    2012-01-16 11:37:14 Y                   RATEMINDEM    10                        2012-01-16 11:37:14 Y                                                              
    2211700 21                     OPSCREW    2012-01-16 11:37:14 Y                   STKREVIEW     9                         2012-01-16 11:37:14 Y                                                              
    2211700 21                     OPSCREW    2012-01-16 11:37:14 Y                   ENGROWIPG     8                         2012-01-16 11:37:14 Y                                                              
    2227510 33                     OPSCREW    2012-08-27 10:50:25 Y                   PAYCOLLECT    21                        2012-08-27 10:51:47 Y                                                              
    2227510 33                     OPSCREW    2012-08-27 10:50:25 Y                   PRESENTVAL    20                        2012-08-27 10:51:44 Y                                                              
    2227510 33                     OPSCREW    2012-08-27 10:50:25 Y                   RATEMINDEM    19                        2012-08-27 10:51:41 Y                                                              
    2227510 33                     OPSCREW    2012-08-27 10:50:25 Y                   CHARGES       9                         2012-08-27 10:51:35 Y                                                              
    2227510 33                     OPSCREW    2012-08-27 10:50:25 Y                   CBMRETIRE     1                         2012-08-27 10:50:45 Y                                                              
    2227515 33                     OPSCREW    2012-08-27 11:01:46 Y                   PAYCOLLECT    21                        2012-08-27 11:03:07 Y                                                              
    2227515 33                     OPSCREW    2012-08-27 11:01:46 Y                   PRESENTVAL    20                        2012-08-27 11:03:04 Y                                                              
    2227515 33                     OPSCREW    2012-08-27 11:01:46 Y                   RATEMINDEM    19                        2012-08-27 11:03:02 Y                                                              
    2227515 33                     OPSCREW    2012-08-27 11:01:46 Y                   CHARGES       9                         2012-08-27 11:02:58 Y                                                              
    2227515 33                     OPSCREW    2012-08-27 11:01:46 Y                   CBMRETIRE     1                         2012-08-27 11:02:08 Y                                                              
    Desire the result set:
    SO NBR  BI_WRKFLW_TASK_SEQ_NBR BI_TASK_CD BI_EVENT_DT_TM      BI_CRITICAL_TASK_SW T2.BI_TASK_CD T2.BI_WRKFLW_TASK_SEQ_NBR T2.BI_EVENT_DT_TM   T2.BI_CRITICAL_TASK_SW                                         
    ------- ---------------------- ---------- ------------------- ------------------- ------------- ------------------------- ------------------- ----------------------                                         
    2211700 21                     OPSCREW    2012-01-16 11:37:14 Y                   ENGWORVIPG    20                        2012-01-16 11:37:14 Y                                                                                                 
    2227510 33                     OPSCREW    2012-08-27 10:50:25 Y                   PAYCOLLECT    21                        2012-08-27 10:51:47 Y                                                                                                 
    2227515 33                     OPSCREW    2012-08-27 11:01:46 Y                   PAYCOLLECT    21                        2012-08-27 11:03:07 Y                                                                                                 
    Thanks for your help!

    :) John

    This sounds like a job for and analytic function. Something like:

    SELECT "SO NBR", BI_WRKFLW_TASK_SEQ_NBR, BI_TASK_CD, BI_EVENT_DT_TM,
           BI_CRITICAL_TASK_SW, "T2.BI_TASK_CD", "T2.BI_WRKFLW_TASK_SEQ_NBR",
           "T2.BI_EVENT_DT_TM", "T2.BI_CRITICAL_TASK_SW"
    FROM (SELECT T1.MSTR_SO_NBR AS "SO NBR",
                 T1.BI_WRKFLW_TASK_SEQ_NBR,
                 T1.BI_TASK_CD,
                 T1.BI_EVENT_DT_TM,
                 T1.BI_CRITICAL_TASK_SW,
                 T2.BI_TASK_CD as "T2.BI_TASK_CD",
                 T2.BI_WRKFLW_TASK_SEQ_NBR as "T2.BI_WRKFLW_TASK_SEQ_NBR",
                 T2.BI_EVENT_DT_TM as "T2.BI_EVENT_DT_TM",
                 T2.BI_CRITICAL_TASK_SW as "T2.BI_CRITICAL_TASK_SW",
                 ROW_NUMBER() OVER (PARTITION BY T1.MSTR_SO_NBR
                                    ORDER BY T2.BI_WRKFLW_TASK_SEQ_NBR desc) rn
          FROM (SELECT DISTINCT BI_SO_MASTER.BI_SO_NBR as "MSTR_SO_NBR",
                                BI_SO_DET_VIEW_1.BI_SO_NBR,
                                BI_WRKFLW_TASKS.BI_WRKFLW_TASK_SEQ_NBR,
                                BI_WRKFLW_TASKS.BI_TASK_CD,
                                BI_WRKFLW_TASKS.BI_EVENT_DT_TM,
                                BI_WRKFLW_TASKS.BI_CRITICAL_TASK_SW
                FROM(XXX)
                  ...) T1
                   LEFT OUTER JOIN (SELECT DISTINCT BI_SO_DET_VIEW_1.BI_SO_NBR,
                                           BI_WRKFLW_TASKS.BI_WRKFLW_TASK_SEQ_NBR,
                                           BI_WRKFLW_TASKS.BI_TASK_CD,
                                           BI_WRKFLW_TASKS.BI_EVENT_DT_TM,
                                           BI_WRKFLW_TASKS.BI_CRITICAL_TASK_SW
                                    FROM(XXX)
                                    ...) T2
                      ON T1.BI_SO_NBR = T2.BI_SO_NBR
          WHERE T2.BI_WRKFLW_TASK_SEQ_NBR < T1.BI_WRKFLW_TASK_SEQ_NBR
            AND T1.BI_SO_NBR IN ('2227510', '2211700', '2227515'))
    WHERE rn = 1
    ORDER BY "SO NBR" ASC, T2.BI_WRKFLW_TASK_SEQ_NBR DESC
    

    John

  • If you select max value using over()

    Hi, I am unable to choose the query below max rated
    could you please help me in this
    with T as 
    (select 100001 ID , 'SLNG' RATING ,  'AA-' RAT_SYBL , 1 TYPE  FROM DUAL UNION ALL
    SELECT 100001   , 'SLNG'   ,  'AA--'  ,   2    FROM DUAL 
    )
    SELECT ID,RATING,CASE WHEN (RATING='SLNG')
                                             THEN  MAX(RAT_SYBL) OVER (PARTITION BY ID)
                                             ELSE NULL
                                             END AS SEL_RATING ,TYPE
     FROM T 
    I have the 2 lines of the above, but I don't need that single line to display
    Thank you

    I don't need that single line to display

    Maybe:

    SQL> with t as (
      select 100001 id, 'SLNG' rating, 'AA-' rat_sybl, 1 type from dual union all
             select 100001, 'SLNG', 'AA--', 2 from dual
    )
    --
    --
    select id, rating, sel_rating, type
      from (select id,
                   rating,
                   rat_sybl,
                   case when (rating = 'SLNG') then max (rat_sybl) over (partition by id) else null end as sel_rating,
                   type
              from t)
     where rat_sybl = sel_rating
    /
            ID RATING SEL_RATING       TYPE
    ---------- ------ ---------- ----------
        100001 SLNG   AA--                2
    1 row selected.
    

    ?

  • How to model in OWB, if you have a subquery in your select statement? (11.2)

    What operator (ie the Table operator) to use if I have a subquery as part of my select statement? (As I do works, but is not elegant. What I do is to create a table for the subquery, and join with other sources to point to my goal.) But, would appreciate the best way with the characteristics of OWB.

    Here is the entire SQL (including the subquery):

    SELECT to_numbe (null), course_id
    at. Book, lp.NAME,
    (by selecting b.pricing in qp_pricing_attributes b
    where b.list_id = ll.list_id and b.product = at.product) sign.
    LL. Operand price, lhb.comments
    Of
    pricing_attribs to,.
    He's list_lines,
    list_h lp,
    Lhb Liste_B
    WHERE 1 = 1
    and ll.list_line_id = atrib.list_line_id
    AND ll.list_header_id = lp.list_header_id
    AND lp.list_header_id = lhb.list_header_id



    Thank you.

    Hello

    Didn't need to be a table in the target. A very simple example, let's say you wanted to do the following:
    Select ename, (select dname dept d where d.deptno = e.deptno) of emp e

    Then DEPT is the table of your choice and EMP is your table of conduct.

    1. Add EMP on the canvas.
    2. Add to the search operator
    3 link research DEPT
    4. tap on finish
    5 card EMP. Department at the Dept. INGRP1 (search operator)
    6. change the search operator, on tab Lookup Conditions for lookup column DEPTNO and DEPTNO of entry attribute
    7. Search full now

    You can add to a table operator target and map of the EMP source table and attributes for release of the search operator. You can change the step 4 to complete the wizard and define the list of choices, but I chose to do 5, to automatically get the names and the data types of the inputs. There are many other options currently in GR 11, 2 in the search.

    Hope it makes sense.

    See you soon
    David

  • SELECT max query

    Hello

    I'm trying to select the record from the scenario below.
    Oracle Database 10 g Enterprise Edition release 10.2.0.3.0 - 64bi
    CREATE TABLE T4
    (
      MID       NUMBER,
      PID       NUMBER,
      SID       VARCHAR2(32 BYTE),
      SUPPLIER  NUMBER,
      UPDT      TIMESTAMP(6),
      EDT       DATE
    )
    
    Insert into T4
       (MID, PID, SID, SUPPLIER, UPDT, EDT)
     Values
       (44333949, 136349891, '36219891030F', 4447, TO_TIMESTAMP('1/1/2010 12:00:00.000000 AM','fmMMfm/fmDDfm/YYYY fmHH12fm:MI:SS.FF AM'), TO_DATE('01/05/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into T4
       (MID, PID, SID, SUPPLIER, UPDT, EDT)
     Values
       (47016634, 670608153, '36219891030F', 4447, TO_TIMESTAMP('1/1/2010 12:00:00.000000 AM','fmMMfm/fmDDfm/YYYY fmHH12fm:MI:SS.FF AM'), TO_DATE('01/01/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into T4
       (MID, PID, SID, SUPPLIER, UPDT, EDT)
     Values
       (44333951, 136349891, '36219891030F', 4447, TO_TIMESTAMP('1/1/2010 12:00:00.000000 AM','fmMMfm/fmDDfm/YYYY fmHH12fm:MI:SS.FF AM'), TO_DATE('01/04/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into T4
       (MID, PID, SID, SUPPLIER, UPDT)
     Values
       (47123075, 670095796, '46919640411M', 4447, TO_TIMESTAMP('4/1/2010 12:00:00.000000 AM','fmMMfm/fmDDfm/YYYY fmHH12fm:MI:SS.FF AM'));
    Insert into T4
       (MID, PID, SID, SUPPLIER, UPDT)
     Values
       (44258745, 137364687, '46919640411M', 4447, TO_TIMESTAMP('1/1/2010 12:00:00.000000 AM','fmMMfm/fmDDfm/YYYY fmHH12fm:MI:SS.FF AM'));
    Insert into T4
       (MID, PID, SID, SUPPLIER, UPDT, EDT)
     Values
       (47123075, 670095796, '46919640412M', 4447, TO_TIMESTAMP('1/1/2010 12:00:00.000000 AM','fmMMfm/fmDDfm/YYYY fmHH12fm:MI:SS.FF AM'), TO_DATE('01/01/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into T4
       (MID, PID, SID, SUPPLIER, UPDT, EDT)
     Values
       (21475309, 28688687, '90820050905M', 4447, TO_TIMESTAMP('4/1/2010 12:00:00.000000 AM','fmMMfm/fmDDfm/YYYY fmHH12fm:MI:SS.FF AM'), TO_DATE('01/04/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into T4
       (MID, PID, SID, SUPPLIER, UPDT, EDT)
     Values
       (45059090, 163943597, '90820050905M', 4447, TO_TIMESTAMP('1/1/2010 12:00:00.000000 AM','fmMMfm/fmDDfm/YYYY fmHH12fm:MI:SS.FF AM'), TO_DATE('01/01/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into T4
       (MID, PID, SID, SUPPLIER, UPDT)
     Values
       (42383558, 97371230, '90820050905M', 4447, TO_TIMESTAMP('5/1/2010 12:00:00.000000 AM','fmMMfm/fmDDfm/YYYY fmHH12fm:MI:SS.FF AM'));
    COMMIT;
    
    Scenario
    
    
    if all Edt is populated pick the latest based on edt  
    
    select * from t4 where sid='46919640412M' and SUPPLIER=4447
    
    MID         PID         SID             SUPPLIER    UPDT         EDT        PICK
    47123075    670095796    46919640412M    4447       1/1/2010     1/1/2010    1
    
    
    if all edt is null pick the latest based on updt 
    
    select * from t4 where sid='46919640411M'  and SUPPLIER=4447
    
    MID             PID         SID         SUPPLIER    UPDT    EDT    PICK
    44258745    137364687    46919640411M    4447    1/1/2010         
    47123075    670095796    46919640411M    4447    4/1/2010           1
    
    
    if edt is populated pick the one based on latest updt with out considering the edt not null 
    select * from t4 where sid='90820050905M'  and SUPPLIER=4447
    
    MID          PID             SID        SUPPLIER        UPDT    EDT             PICK
    45059090    163943597    90820050905M    4447        1/1/2010   1/1/2010    
    42383558    97371230    90820050905M    4447        5/1/2010                    1
    21475309    28688687    90820050905M    4447        4/1/2010    1/4/2010    
    
    if all edt is found pic the latest based on edt. 
    
    select * from t4 where sid='36219891030F'  and SUPPLIER=4447
    
    
    MID         PID             SID         SUPPLIER    UPDT         EDT        PICK
    47016634    670608153    36219891030F    4447     1/1/2010     1/1/2010    
    44333949    136349891    36219891030F    4447     1/1/2010     1/5/2010       1
    44333951    136349891    36219891030F    4447     1/1/2010     1/4/2010    
    I tried like this its not satisfying all the scenarios.


    SOME mediums,
    nest,
    SID,
    provider,
    Shift,
    EDT,
    ROW_NUMBER)
    MORE THAN
    (
    ORDER BY CASE WHEN edt IS NOT NULL THEN ELSE END DESC edt SYSDATE
    )
    Pick
    T4
    WHERE sid = '36219891030F' AND provider = 4447


    Thank you

    Alen

    With the help of analytical functions;

    select sid,
           supplier,
           updt,
           edt,
           case
              when (cnt_edt = cnt_all and edt = max_edt)
                   or (cnt_edt != cnt_all and updt = max_updt) then
               1
            end pick1
    from (select t4.*,
                 count(edt) over(partition by sid, supplier) cnt_edt,
                 count(*) over(partition by sid, supplier) cnt_all,
                 max(updt) over(partition by sid) max_updt,
                 max(edt) over(partition by sid) max_edt
          from t4)
    order by 1,2,3,4;
    
    SID             SUPPLIER UPDT                      EDT         PICK1
    ------------- ---------- ------------------------- ----------- -----
    36219891030F        4447 10-01-01 00:00:00,000000  01/01/2010
    36219891030F        4447 10-01-01 00:00:00,000000  04/01/2010
    36219891030F        4447 10-01-01 00:00:00,000000  05/01/2010      1
    46919640411M        4447 10-01-01 00:00:00,000000
    46919640411M        4447 10-04-01 00:00:00,000000                  1
    46919640412M        4447 10-01-01 00:00:00,000000  01/01/2010      1
    90820050905M        4447 10-01-01 00:00:00,000000  01/01/2010
    90820050905M        4447 10-04-01 00:00:00,000000  04/01/2010
    90820050905M        4447 10-05-01 00:00:00,000000                  1
    

    Edited by: MScallion may 7, 2010 14:24 - replaced braces with! =

Maybe you are looking for

  • 1. in the most visited past bad worked. 2 but a week is totally gone and I can not restorere with

    1. in the past the most visited worked poorly, often disappear, but I can restore with view, toolbar, customize, restore default set.2, but last week the most visited toally lost one it is imposibble to restore.

  • wiring

    There is a drawing that shows the wire that goes where, on a hp m370n? mainly from the Panel of the motherboard

  • Microsoft support scam / Virtual PC Doctor

    I was called by someone claiming to be from Microsoft technical supportringing to warn me automatically downloaded the files that would be 'eat' my computer - he used terms tech more, but I am not very computer and this is the problem! I turned on my

  • The exit of the inner loop program

    Hi im new to Labview so that it sounds like an easy problem to solve. I'm simulating a signal and display on a graph when I click on a start button. But I can't understand how, to always be able to get out all of the output of a button program as im

  • Ctrl-Alt-Delete keyboard shortcuts

    Are there any keyboard shortcuts once you press ctrl-alt-del? I'm used to my computer with ctrlaltdel-k locking. Since then, I have noticed that there are no shortcuts. Has been removed this feature, scheduled to enter or what. Miss me it already, or