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

Tags: Database

Similar Questions

  • 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.
    

    ?

  • Need to get Max Value day in a table with hourly data of SQL

    I have a table "tmp" with these columns:

    ID, date, time, value

    I want to get the 'time' when 'value' max is reached in each 'day '.

    the query:

    "SELECT id, day, hour, max (value) from group tmp by id, date, time"
    does not return the desired lines.

    You have an idea to get what I want?

    Maybe this:

    with tmp as
    ( select 1 id, trunc(sysdate) day, 10 hour, 100 value from dual union all
      select 2 id, trunc(sysdate) day, 11 hour, 110 value from dual union all
      select 3 id, trunc(sysdate) day, 12 hour, 120 value from dual union all
      select 4 id, trunc(sysdate) day, 13 hour, 130 value from dual union all
      select 5 id, trunc(sysdate-1) day, 10 hour, 100 value from dual union all
      select 6 id, trunc(sysdate-1) day, 11 hour, 90 value from dual union all
      select 7 id, trunc(sysdate-1) day, 12 hour, 150 value from dual union all
      select 8 id, trunc(sysdate-1) day, 13 hour, 100 value from dual )
    Select ID, Day, Hour, Value
    From Tmp
    Where (Day, Value) IN (
    Select Day, Max(Value)
    From Tmp
    Group by Day)
    

    Results:

            ID DAY             HOUR      VALUE
    ---------- --------- ---------- ----------
             7 08-DEC-08         12        150
             4 09-DEC-08         13        130
    
    2 rows selected.
    

    Kind regards
    Miguel

  • Get the max value with other areas

    Hi all

    I have a table as below

    Value name
    - - - - - - - - - - - - - - - -
    A1 5
    A3 10
    A2 7
    A2 9
    A1 10

    What I get is the max (Value) and with the consolidation of its name

    Value name
    - - - - - - - - -
    A2 16

    Thank you
    Alex

    Published by: user8606416 on June 1, 2011 10:17

    Published by: user8606416 on June 1, 2011 10:26

    Depends on how you feel on one of the links of:

    SELECT name, value
    FROM (SELECT name, SUM(value)
          FROM table
          GROUP BY name
          ORDER BY 2 DESC)
    WHERE rownum = 1
    
    SELECT name, SUM(value)
    FROM table
    GROUP BY name
    HAVING SUM(value) >= ALL (SELECT SUM(value)
                              FROM table
                              GROUP BY name)
    

    among many other methods. The first takes a single arbitrary registration in the case of a tie, and the second shows all the related records.

    John

  • Need to get the latest news for a group-max (value) of the non-null values

    Hello

    Here is my table and data

    SQL > desc method

    NUMBER OF SEQ_ID
    EMP_ID NUMBER
    ISSUE GUID
    FIRST NAME VARCHAR2 (30)
    LAST_NAME VARCHAR2 (30)
    E-MAIL VARCHAR2 (45)
    PHONENO VARCHAR2 (30)

    SQL > Select * method;

    SEQ_ID EMP_ID GUID FIRST_NAME LAST_NAME EMAIL PHONENO
    ------ - ----- ---- --------- --------------------------------------------------- ----------------------------------------- ------------------------------
    1 100 20 RAJA HHH 686678
    2 100 20 [email protected]
    3 100 20 RAJA 134555
    4 100 20 HAPPY [email protected]
    5 200 20 RAM
    6 200 20 JJJ 2345667
    7 200 20 RM GGG [email protected] 1234557
    8 200 20 [email protected] RRR

    8 selected lines


    I want the latest news on the employee, the group id comibnation for the rest of the columns.

    So I want to get the following result.

    100 20 RAVI HHH [email protected] 134555

    200 20 RRR GGG [email protected] 1234557


    If you note here for the family name, we take the previous value non-zero value Eg HHH column and is the same for all columns.

    It's the value of line max (seqid) for empid, combination of guid and if the column values are null, we must get the previous maximum value non-zero.

    The seqid is also there that the sequence.

    Please help me to get the result set.

    Thanks in advance.

    mjhraja.
    SQL> select emp_id, guid, max(first_name) first_name, max(last_name) last_name
      2    , max(email) email, max(phoneno) phoneno
      3  from (
      4    select emp_id, guid
      5      , first_value (first_name ignore nulls)
      6          over (partition by emp_id, guid order by seq_id desc) first_name
      7      , first_value (last_name ignore nulls)
      8          over (partition by emp_id, guid order by seq_id desc) last_name
      9      , first_value (email ignore nulls)
     10          over (partition by emp_id, guid order by seq_id desc) email
     11      , first_value (phoneno ignore nulls)
     12          over (partition by emp_id, guid order by seq_id desc) phoneno
     13    from emp_info
     14  )
     15  group by emp_id, guid
     16  /
    
        EMP_ID GUID FIRST_NAME LAST_NAME  EMAIL                PHONENO
    ---------- ---- ---------- ---------- -------------------- ----------
           100   20 RAVI       HHH        [email protected]         134555
           200   20 RRR        GGG        [email protected]       1234557
    
    SQL> 
    
  • SQL, find the MAX value and placing it as a QVariant

    I have a database that is loaded and defines the customerID as 0 which is ideal when the database is not be saved and restored, etc.  The question I have is that I added the possibility to users to restore a backup in the app, and now I have to do a query to select MAX (customerID) so that there is no duplicate CustomerID when you add or save items.  Here is the following code, I knew that I must settle, specifically the 0 highlighted in red.  I need zero to be the new customerID max value:

    int SettingsStorage::load(int& lastID, GroupDataModel *model)
    {
        // number of locations loaded.
        QSettings settings(m_author, m_appName);
        int loadedCount = 0;
    
        QVariant items;
        // Get the last customer id first.
        // ID's will be generated by incrementing this number
        // Note values coming from settings should be cast to the
        // required type.
         lastID = settings.value(m_lastCustomerIDKey, 0).toInt();
        items = m_sda->execute("SELECT * from items ORDER BY datefield");
        qDebug()<< "the ID" << items;
        // Load all the locations from the database.
        foreach( const QVariant& temp, items.value() ) {
            Location *p;
            if (loadLocation(temp.value(), p)) {
                model->insert(p);
                loadedCount++;
            }
        }
        return loadedCount;
    }
    

    Ive tried the following, but it doesn't seem to do anything:

    int SettingsStorage::load(int& lastID, GroupDataModel *model)
    {
        // number of locations loaded.
        QSettings settings(m_author, m_appName);
        int loadedCount = 0;
    
        QVariant items;
        // Get the last customer id first.
        // ID's will be generated by incrementing this number
        // Note values coming from settings should be cast to the
        // required type.
         QVariant endID = m_sda->execute("Select MAX(customerID) from items")
         lastID = settings.value(m_lastCustomerIDKey, endID).toInt();
        items = m_sda->execute("SELECT * from items ORDER BY datefield");
        qDebug()<< "the ID" << items;
        // Load all the locations from the database.
        foreach( const QVariant& temp, items.value() ) {
            Location *p;
            if (loadLocation(temp.value(), p)) {
                model->insert(p);
                loadedCount++;
            }
        }
        return loadedCount;
    }
    

    Any help will be loved and marked solutions.

    -Thanks in advance

    I was wrong about executeAndWait(). Somehow, I decided that you use the SqlConnection object, but seems his SqlDataAccess. So disregard my previous post. Keep your execute method, but you must change your code to something like this:

    QVariant endID = m_sda->execute("select max(customerID) as m from items");
    
    QVariantList vlist = endID.value();
    QVariantMap vmap = vlist.first().toMap();
    
    lastID = vmap["m"].toInt(&ok);
    

    So I changed your SQL query slightly and added "that m" so I will have something to refer later.

    Then I cast QVariantList because it is where are the results.

    Then because we know its going to be the only record, I took the 1st element in the list and converted to QVariantMap.

    Last step is to get the maximum.

    Should work this time

  • select statement nested within the group to get the owner of max

    Hello

    I have a table with columns ID, PAGE_NUM, MOD_DATE, USER_ID, etc..

    I want a single query which groups recorded by PAGE_NUM and return lines as follows:

    PAGE_NUM, count (PAGE_NUM), max (MOD_DATE) and USER_ID associated with max (MOD_DATE).

    I can make three 1, but do not know how to get the USER_ID associated with max (MOD_DATE) in a query. Maybe its faster when even make 2 requests?

    Andy

    Hello

    user9990110 wrote:
    Hello

    I use Oracle + Hibernate. Hibernation uses HQL which is the most common subset of sql. Then she runs through a parser to convert in SQL for Oracle. I think that this request should be friendly HQL, and I go search if the LAST is supported or not. Otherwise, it must be a scalar subquery, and that's what I was trying to figure out how to do when I posted. I didn't know that there is a faster way without the subquery. In addition, Hibernate has a native SQL mode too, but I found that it works the native sql through his monitor too, and if she doesn't like him for some reason, it throws an exception. So I'm not sure LAST will work for me, and I know that don't TopN.

    All this sounds like a good reason to use a view. Hibernation will think that you simply reference another table.

    So if you could show me the scalar subquery..., I know working with Hibernate.

    Here is how to do this with a scalar subquery:

    SELECT       page_num
    ,       COUNT (page_num)     AS cnt
    ,       MAX (mod_date)     AS last_mod_date
    ,       (   SELECT  MIN (user_id)
               FROM    table_x     s
               WHERE   page_num     = x.page_num
               AND     mod_date     = ( SELECT  MAX (mod_date)
                                        FROM    table_x
                            WHERE   page_num     = s.page_num
                          )
           )                        AS last_mod_user_id
    FROM       table_x     x
    GROUP BY  page_num
    ;
    

    Furthermore, what does DENSE_RANK?

    Nothing of what I know. It is a mandatory keyword that should be used with the FIRST and LAST. (It is not identical to the analytical DENSE_RANK function.)

    Is it possible to write your original with LAST request but without dense_rank?

    N °

  • Select the MAX value

    My goal here is to select the id of the half of the class more recently taken for a given student. Are the session id in the format (1, yy, 2/5/7 - spring, and autumn)-, 2004 summer semester would be 1045. A half of 1095 ID would be newer than that of 1042.

    I wrote the following, but it doesn't quite know how I want it. He returned several lines where ideally he doesn't return a single line. I tried to limit 1 and some other things around him, but I always get an error whenever I try to run that. I also tried to add ' where rowcount < 2 "but this 1045 statements, not 1095. I think it gets the number of rows before it does the calculation of MAX.

    Any ideas?
    select MAX(grades.semester_id)
    from grades
    join requirements
    on (grades.COURSE_ID=requirements.COURSE_ID)
    where requirements.CERT_ID = '1'
    and student_id = '0000006'
    group by grades.course_id

    Hello

    Try this:

    SELECT grades.semester_id
      FROM grades
      JOIN requirements ON (grades.COURSE_ID = requirements.COURSE_ID)
     WHERE requirements.CERT_ID = '1'
       AND student_id = '0000006'
       AND rownum <= 1
     ORDER BY grades.semester_id DESC
    

    Kind regards

  • 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
    
  • Update based on the max value of different tables.

    {code}

    create the table rule_table (number rule_id);

    insert into rule_table values (10);

    insert into rule_table values (20);

    insert into rule_table values (30);

    insert into rule_table values (40);

    create the table auth_table (number of auth_id, rule_id number);

    insert into auth_table values (1000, 10);

    insert into auth_table values (2000, 10);

    insert into auth_table values (3000, 10);

    insert into auth_table values (4000, 20);

    insert into auth_table values (5000, 20);

    insert into auth_table values (6000, 30);

    insert into auth_table values (7000, 30);

    insert into auth_table values (8000, 40);

    insert into auth_table values (9000, 40);

    create the table pay_table (pay_id number, auth_id number, pay_indicator number);

    insert into pay_table values (11111, 1000, 0);

    insert into pay_table values (22222, 1000, 1);

    insert into pay_table values (33333, 1000, 0);

    insert into pay_table values (44444, 2000, 0);

    insert into pay_table values (55555, 2000, 1).

    insert into pay_table values (66666, 2000, 0);

    insert into pay_table values (77777, 3000, 0);

    insert into pay_table values (88888, 3000, 0);

    insert into pay_table values (99999, 4000, 0);

    insert into pay_table values (111111, 4000, 0);

    insert into pay_table values (222222, 5000, 0);

    insert into pay_table values (333333, 5000, 0);

    insert into pay_table values (444444, 6000, 0);

    insert into pay_table values (555555, 7000, 1);

    insert into pay_table values (666666, 8000, 0);

    insert into pay_table values (777777, 9000, 0);

    insert into pay_table values (888888, 9000, 1);

    create the table rule_pay (rule_id number, pay_max_indicator number);

    insert into rule_pay values (10, 0);

    insert into rule_pay (20, 0) values;

    insert into rule_pay (30, 0) values;

    insert into rule_pay (40, 0) values;

    {code}

    My intention is:

    for every find of rule_id on the maximum pay_indicator (tables 3 query to get the max Show pay_indicator below) and on the other table I have to update this value max based on rule_id.

    with max_tab

    as

    (

    Select a.rule_id, max (pay_indicator) pay_indicator

    rule_table a.,

    b auth_table,

    c pay_table

    where a.rule_id = b.rule_id

    and b.auth_id = c.auth_id

    A.rule_id group

    )

    Update rule_pay

    Set pay_max_indicator = (select max_tab.pay_indicator

    of max_tab

    where max_tab.rule_id = rule_pay.rule_id)

    where

    rule_id in (select rule_id from max_tab);

    The above query does not.

    Any help or suggestions are greatly appreciated.

    Something like that?

    SQL > select * from rule_pay;

    RULE_ID PAY_MAX_INDICATOR

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

    10                    0

    20                    0

    30                    0

    40                    0

    SQL > fusion in rule_pay PR

    2. using (select a.rule_id, max (pay_indicator) pay_indicator

    rule_table 3A,

    auth_table 4 b,

    pay_table 5 c

    6 where a.rule_id = b.rule_id

    7 and b.auth_id = c.auth_id

    Group 8 by a.rule_id

    9        ) u

    10 on (u.rule_id = rp.rule_id)

    11 when matched, then update

    12 set rp.pay_max_indicator = u.pay_indicator

    13;

    4 lines merged.

    SQL > select * from rule_pay;

    RULE_ID PAY_MAX_INDICATOR

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

    10                    1

    20                    0

    30                    1

    40                    1

    BTW, you can't put a WITH clause before an update.  It can only precede a select statement.

  • mark the first value of a group

    I get the following
    16:57:28 >r
      1  with my_table as
      2       (
      3      select 'M082012' pera, to_number(10584338) snr, to_number(10) pnr, 'Beule' name, 'Anna' f_name from dual union all
      4      select 'M092012' pera, to_number(15965177) snr, to_number(15) pnr, 'Tester' name, 'Toni' f_name from dual union all
      5      select 'M082012' pera, to_number(14254501) snr, to_number(20) pnr, 'Wallen' name, 'Monika' f_name from dual union all
      6      select 'M082012' pera, to_number(10584339) snr, to_number(10) pnr, 'Beule' name, 'Anna' f_name from dual union all
      7      select 'M092012' pera, to_number(15965178) snr, to_number(10) pnr, 'Beule' name, 'Anna' f_name from dual union all
      8      select 'M012013' pera, to_number(10674833) snr, to_number(15) pnr, 'Tester' name, 'Toni' f_name from dual union all
      9      select 'M012013' pera, to_number(10674834) snr, to_number(15) pnr, 'Tester' name, 'Toni' f_name from dual union all
     10      select 'M012013' pera, to_number(10539210) snr, to_number(30) pnr, 'Klose' name, 'Werner' f_name from dual union all
     11      select 'M012013' pera, to_number(12345678) snr, to_number(50) pnr, 'Meier' name, 'Otto' f_name from dual union all
     12      select 'M012013' pera, to_number(22345789) snr, to_number(50) pnr, 'Meier' name, 'Otto' f_name from dual union all
     13      select 'M082012' pera, to_number(10584346) snr, to_number(77) pnr, 'Carl' name, 'Frank' f_name from dual union all
     14      select 'M062012' pera, to_number(10550971) snr, to_number(77) pnr, 'Carl' name, 'Frank' f_name from dual union all
     15      select 'M092012' pera, to_number(15965185) snr, to_number(77) pnr, 'Carl' name, 'Frank' f_name from dual union all
     16      select 'M082012' pera, to_number(10584352) snr, to_number(50) pnr, 'Meier' name, 'Otto' f_name from dual union all
     17      select 'M092012' pera, to_number(15965191) snr, to_number(80) pnr, 'Duster' name, 'Hucke' f_name from dual)
     18  select case when pera = 'M012013' then '*' end mark,
     19         pera, snr, pnr, name, f_name
     20  from (
     21        select pera, snr, pnr, name, f_name,
     22               max(case when pera = 'M012013' then 'Y' end)
     23                 over(partition by upper(name||f_name)) m_flag,
     24               count(*) over(partition by upper(name||f_name)) cnt
     25        from my_table
     26       )
     27  where m_flag = 'Y'
     28  and cnt > 1
     29* order by 4,5,6, to_number(substr(pera,4,4)||substr(pera,2,2)) desc
    
    MARK  PERA           SNR        PNR NAME   F_NAME
    ----- ------- ---------- ---------- ------ ------
    *     M012013   10674834         15 Tester Toni
    *     M012013   10674833         15 Tester Toni
          M092012   15965177         15 Tester Toni
    *     M012013   22345789         50 Meier  Otto
    *     M012013   12345678         50 Meier  Otto
          M082012   10584352         50 Meier  Otto
    I would like to mark only the first value in the group with an asterisk as follows.
    MARK  PERA           SNR        PNR NAME   F_NAME
    ----- ------- ---------- ---------- ------ ------
    *     M012013   10674834         15 Tester Toni
          M012013   10674833         15 Tester Toni
          M092012   15965177         15 Tester Toni
    *     M012013   22345789         50 Meier  Otto
          M012013   12345678         50 Meier  Otto
          M082012   10584352         50 Meier  Otto

    Perhaps this example might be useful for you. the code uses the same code that you published with additional analytical query to return the row grouping for the name, the NRP and columns pera. then use that line number to determine which will be placed at the first mark.

    SQL>   with my_table as
      2         (
      3        select 'M082012' pera, to_number(10584338) snr, to_number(10) pnr, 'Beule' name, 'Anna' f_name from dual union all
      4        select 'M092012' pera, to_number(15965177) snr, to_number(15) pnr, 'Tester' name, 'Toni' f_name from dual union all
      5        select 'M082012' pera, to_number(14254501) snr, to_number(20) pnr, 'Wallen' name, 'Monika' f_name from dual union all
      6        select 'M082012' pera, to_number(10584339) snr, to_number(10) pnr, 'Beule' name, 'Anna' f_name from dual union all
      7        select 'M092012' pera, to_number(15965178) snr, to_number(10) pnr, 'Beule' name, 'Anna' f_name from dual union all
      8        select 'M012013' pera, to_number(10674833) snr, to_number(15) pnr, 'Tester' name, 'Toni' f_name from dual union all
      9        select 'M012013' pera, to_number(10674834) snr, to_number(15) pnr, 'Tester' name, 'Toni' f_name from dual union all
     10        select 'M012013' pera, to_number(10539210) snr, to_number(30) pnr, 'Klose' name, 'Werner' f_name from dual union all
     11        select 'M012013' pera, to_number(12345678) snr, to_number(50) pnr, 'Meier' name, 'Otto' f_name from dual union all
     12        select 'M012013' pera, to_number(22345789) snr, to_number(50) pnr, 'Meier' name, 'Otto' f_name from dual union all
     13        select 'M082012' pera, to_number(10584346) snr, to_number(77) pnr, 'Carl' name, 'Frank' f_name from dual union all
     14        select 'M062012' pera, to_number(10550971) snr, to_number(77) pnr, 'Carl' name, 'Frank' f_name from dual union all
     15        select 'M092012' pera, to_number(15965185) snr, to_number(77) pnr, 'Carl' name, 'Frank' f_name from dual union all
     16        select 'M082012' pera, to_number(10584352) snr, to_number(50) pnr, 'Meier' name, 'Otto' f_name from dual union all
     17        select 'M092012' pera, to_number(15965191) snr, to_number(80) pnr, 'Duster' name, 'Hucke' f_name from dual)
     18    select case when pera = 'M012013' and rn = 1 then '*' end mark,
     19           pera,
     20           snr,
     21           pnr,
     22           name,
     23           f_name
     24      from (select pera, snr, pnr, name, f_name,
     25                   row_number() over (partition by pera, pnr, name, f_name order by pera, pnr, name) rn
     26              from (select pera, snr, pnr, name, f_name,
     27                           max(case when pera = 'M012013' then 'Y' end)
     28                           over(partition by upper(name||f_name)) m_flag,
     29                           count(*) over(partition by upper(name||f_name)) cnt
     30                      from my_table)
     31                     where m_flag = 'Y'
     32                       and cnt > 1
     33             order by 4,5,6, to_number(substr(pera,4,4)||substr(pera,2,2)) desc)
     34    order by 4,5,6, to_number(substr(pera,4,4)||substr(pera,2,2)) desc;
    
    MARK PERA           SNR        PNR NAME   F_NAME
    ---- ------- ---------- ---------- ------ ------
    *    M012013   10674834         15 Tester Toni
         M012013   10674833         15 Tester Toni
         M092012   15965177         15 Tester Toni
    *    M012013   22345789         50 Meier  Otto
         M012013   12345678         50 Meier  Otto
         M082012   10584352         50 Meier  Otto
    
    6 rows selected
    
    SQL> 
    
  • 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.

  • 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)
    
  • Max value return value despite where clause is not not really looking for the reason

    Hello

    Using oracle 11.2.0.3

    Select 'A '.

    of the double

    where 1 = 2

    No returns no row, as expected

    Select max ('A')

    of the double

    where 1 = 2 - that is to say isn't true

    Returns the line with null

    Why is this?

    Thank you

    Hello

    user5716448 wrote:

    Hello

    Thanks for the reply.

    I guess that's rule ageneral wait even if no line because of the place where the condition.

    where 1 = 2 - that is to say isn't true

    Thank you

    Yes, if there are no rows in the table, or no line meets the conditions in the WHERE clause, it would be logical that the query return lines exactly 0, but it is also logical that the query returns exactly 1 row.  People who have designed SQL apperantly thought return 1 row was most helpful.

    If you want the query to return 0 rows when there is no data, you can GROUP BY a constant.  For example:

    SELECT MAX (hiredate) AS last_hitedate

    FROM scott.emp

    WHERE deptno = & deptno_wanted

    GROUP 0

    ;

    If there are any rows that meet the condition in the WHERE clause, then the query will produce 1 row, but if no rows meet this condition, then the query will return 0 rows.

    Personally, I'm happy that they designed this way SQL.  I find it rather convenient that the aggregates without GROUP BY clause will return 1 row.  I do things like

    SELECT COUNT (*)

    FROM table_x;

    often, when I want to know if a table has been filled or not.  Seeing a 0 for the output is much clearer that does not get any results.

  • 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

Maybe you are looking for

  • Cannot sync with I - Mac

    When you try to back up or synchronize 6 I - Pod or I-phone version 6 for 2011 I have Mac, receive error message "wrong answer received from the device."  I - Tunes does not recognize the device. Have reset tried hard and soft, I tried different cabl

  • "Important deleted" what is it?

    HelloI've seen this several times but no idea what it is...From time to time, I see the message "2 messages deleted from the important".Possible not the exact phrase as it is quite a small message. OK where is "Important".Why I can't find deleted gar

  • After update Ubuntu 12.04, address/search in Firefox 29,0 bar behaves strangely. Clues?

    I see that some users complain their upgrade 29,0 Firefox Mozilla having questions about the address/search bar, but in my case the update 29,0 Firefox itself ran smoothly and flawless until the last Ubuntu 12.04 automatic update triggered by the net

  • Adapter Kit Apple World Traveller is not about the Iphone.  What devices can I reload Iphone foreign 6s

    What devices do I need recharge my IPhone aboard safely?  The adapters Apple world traveler Kit does not have the I phone.  Do I need a separate transformer to step down the voltage from 240 to 110? or does multi auto power?

  • iPad battery Mini after update iOS9.3

    Hi all I have a Mini iPad (1st generation). Until I upgraded to iOS9.3, everything worked well. With the new iOS9.3, drains the battery overnight, even if the iPad Mini is not used. Settings-> battery-> use information indicate that in the last 24 ho