Analytical function syntax help

The following query sorts by most occuring hesid descedning and requires TWO full table scans of the episodes_full_test table :
create table episodes_full_test (epikey number, hesid number, dob date) tablespace analysis_ip_d;
insert into episodes_full_test values (100, 20, to_date('31-07-1975','DD-MM-YYYY'));
insert into episodes_full_test values (101, 20, to_date('31-07-1975','DD-MM-YYYY'));
insert into episodes_full_test values (102, 20, to_date('31-07-1975','DD-MM-YYYY'));
insert into episodes_full_test values (103, 20, to_date('31-07-1975','DD-MM-YYYY'));
insert into episodes_full_test values (104, 10, to_date('31-07-1985','DD-MM-YYYY'));
insert into episodes_full_test values (105, 30, to_date('31-07-1995','DD-MM-YYYY'));
insert into episodes_full_test values (106, 30, to_date('31-07-1995','DD-MM-YYYY'));
insert into episodes_full_test values (107, 30, to_date('31-07-1995','DD-MM-YYYY'));
commit;
select eft.hesid, eft.epikey, eft.dob
from episodes_full_test eft
join (select hesid, count(hesid) count_hesid
from episodes_full_test
group by hesid) v1
on eft.hesid = v1.hesid
order by v1.count_hesid desc, eft.epikey;     
HESID EPIKEY DOB
20 100 31/07/1975
20 101 31/07/1975
20 102 31/07/1975
20 103 31/07/1975
30 105 31/07/1995
30 106 31/07/1995
30 107 31/07/1995
10 104 31/07/1985
I'm sure there's a way to use analytical functions such that Oracle only needs to perform ONE full table scan of episodes_full_test, but I can't figure out the syntax
Can anyone advise please ?
(Oracle 9r2)
Thanks, Gus

Thank you for providing the create table, insert commands and required output as it makes answering the question much easier (once I'd removed the tablespace specification)
SQL> select hesid, epikey, dob
  2  from
  3      (
  4      select eft.hesid, eft.epikey, eft.dob,
  5          count(*) over (partition by eft.hesid) count_hesid
  6      from episodes_full_test eft
  7      )
  8  order by count_hesid desc;
     HESID     EPIKEY DOB
        20        100 31-JUL-75
        20        101 31-JUL-75
        20        102 31-JUL-75
        20        103 31-JUL-75
        30        105 31-JUL-95
        30        106 31-JUL-95
        30        107 31-JUL-95
        10        104 31-JUL-85
8 rows selected.
SQL>

Similar Messages

  • How to achive this using analytical function-- please help

    version 10g.
    this code works just fine with my requirement. i am tyring to learn analytical functions and implement that in the below query. i tried using row_number ,
    but i could nt achive the desired results. please give me some ideas.
    SELECT c.tax_idntfctn_nmbr irs_number, c.legal_name irs_name,
           f.prvdr_lctn_iid
      FROM tax_entity_detail c,
           provider_detail e,
           provider_location f,
           provider_location_detail pld
    WHERE c.tax_entity_sid = e.tax_entity_sid
       AND e.prvdr_sid = f.prvdr_sid
       AND pld.prvdr_lctn_iid = f.prvdr_lctn_iid
       AND c.oprtnl_flag = 'A'
       AND c.status_cid = 2
       AND e.oprtnl_flag = 'A'
       AND e.status_cid = 2
       AND (c.from_date) =
              (SELECT MAX (c1.from_date)
                 FROM tax_entity_detail c1
                WHERE c1.tax_entity_sid = c.tax_entity_sid
                  AND c1.oprtnl_flag = 'A'
                  AND c1.status_cid = 2)
       AND (e.from_date) =
              (SELECT MAX (c1.from_date)
                 FROM provider_detail c1
                WHERE c1.prvdr_sid = e.prvdr_sid
                  AND c1.oprtnl_flag = 'A'
                  AND c1.status_cid = 2)
       AND pld.oprtnl_flag = 'A'
       AND pld.status_cid = 2
       AND (pld.from_date) =
              (SELECT MAX (a1.from_date)
                 FROM provider_location_detail a1
                WHERE a1.prvdr_lctn_iid = pld.prvdr_lctn_iid
                  AND a1.oprtnl_flag = 'A'
                  AND a1.status_cid = 2)thanks
    Edited by: new learner on May 24, 2010 7:53 AM
    Edited by: new learner on May 24, 2010 10:50 AM

    May be like this not tested...
    select *
    from
    SELECT c.tax_idntfctn_nmbr irs_number, c.legal_name irs_name,
    f.prvdr_lctn_iid, c.from_date as c_from_date, max(c.from_date) over(partition by c.tax_entity_sid) as max_c_from_date,
    e.from_date as e_from_date, max(e.from_date) over(partition by e.prvdr_sid) as max_e_from_date,
    pld.from_date as pld_from_date, max(pld.from_date) over(partition by pld.prvdr_lctn_iid) as max_pld_from_date
    FROM tax_entity_detail c,
    provider_detail e,
    provider_location f,
    provider_location_detail pld
    WHERE c.tax_entity_sid = e.tax_entity_sid
    AND e.prvdr_sid = f.prvdr_sid
    AND pld.prvdr_lctn_iid = f.prvdr_lctn_iid
    AND c.oprtnl_flag = 'A'
    AND c.status_cid = 2
    AND e.oprtnl_flag = 'A'
    AND e.status_cid = 2
    AND pld.oprtnl_flag = 'A'
    AND pld.status_cid = 2
    )X
    where c_from_date=max_c_from_date AND e_from_date =max_e_from_date AND
    pld_from_date=max_pld_from_date

  • Analytic function sql help

    Table with 2 columns pro_id,sub_ver_id. Need only 5 pro_id for each sub_ver_id
    SQL> select * from test1 order by SUB_VER_ID;
    PRO_ID SUB_VER_ID
    1 0
    2 0
    3 0
    4 0
    5 0
    6 0
    10 1
    15 1
    16 1
    11 1
    12 1
    PRO_ID SUB_VER_ID
    13 1
    14 1
    11 2
    12 3
    I'm new to analytic function i got query as below, but not able to get an idea to limit the SRLNO to only 5 rows for each SUB_VER_ID. Any hint would be much appreciated.
    select distinct sub_ver_id,pro_id, row_number () over (order by sub_ver_id) srlno
    from test1 order by sub_ver_id

    May be as below..
    select *
    from
    select sub_ver_id,pro_id, row_number () over (partition by sub_ver_id order by null) srlno
    from test1
    ) where srlno <=5 order by sub_ver_idThanks...

  • PL/SQL Function Syntax help please...

    Can someone help me with the syntax here please? I am sure i am doing something wrong in my LOOP.
    create or replace FUNCTION fcn_chk_dec(p_date number)
    return NUMBER
    as
    --DECLARE
    v_date NUMBER;
    v_active NUMBER;
    v_prev NUMBER;
    v_delta NUMBER;
    v_perc_delta NUMBER:
    CURSOR c_prev_active IS
         select date,people,
    lag(people,1) over (order by date)
         from stats
    where date between to_date(p_date, 'YYYYMMDD')-2 and to_date(p_date, 'YYYYMMDD')-1
         order by date desc
    BEGIN
         OPEN c_prev;
    loop
         FETCH c_prev INTO v_date,v_active,v_prev;
         exit when c_prev%NOTFOUND;
         v_delta:=v_active-v_prev;
    v_perc_delta:=trunc((v_delta/v_active*100),2)
    end loop;
    close c_prev;
    return v_perc_delta;
    END fcn_chk_dec;

    what i am trying to do is create a funtion that will return one value for the first row that comes back.
    here is my initial query. the reason i did not go with this query is because there are too many selects and i was told that's not good and slows down the system. Plus, i need to have a function call in another program that will access this function to compare it's output to a value in a table.
    here was my initial start:
    select date,people,delta,trunc((delta/people*100),2) as perc_delta
    from (select date, people,people-prev_dly_people as delta
    from
    (select date,people,
    lag(people,1) over (order by date) as prev_dly_people
    from stats
    where date between to_char(sysdate-2,'YYYYMMDD') and to_char(sysdate-1,'YYYYMMDD')
    order by date desc))
    basically, i have a table that has a total number of people. I want to get the percentage growth and decline from the most recent date and the date before it. This will give me a day to day percentage of people population change as of the most recent date.
    I need this to be a function becaus i want to be able to pass any date i want into it and get the given delta percentage at the time for the people's population.
    hope this makes sense.

  • How to achive using analytical functions -- please help

    oracle version : 10g
    -- 999 means ALL values for that key
    with input_parameters as (select 10 filter_key , '10ACCC' filter_value from dual union all
    select 50 filter_key ,'10ACCC0001' filter_value from dual union all
    select 60 filter_key , 'PIP' filter_value from dual union all
    select 70 filter_key , 'A' filter_value from dual) select * from input_parameters;
    with profile_search as(
    select 100 profile_id , 10 filter_key , '10ACCC' filter_value from dual union all
    select 100 profile_id , 50 filter_key , '10ACCC0001' filter_value from dual union all
    select 100 profile_id , 50 filter_key , '10ACCC0002' filter_value from dual union all
    select 100 profile_id , 60 filter_key , '999' filter_value from dual union all
    select 100 profile_id , 70 filter_key , '999' filter_value from dual union all
    select 101 profile_id , 10 filter_key , '10ACCC' filter_value from dual union all
    select 101 profile_id , 50 filter_key , '10ACCC001' filter_value from dual union all
    select 101 profile_id , 60 filter_key , 'PIP' filter_value from dual union all
    select 101 profile_id , 70 filter_key , '999' filter_value from dual union all
    select 102 profile_id , 10 filter_key , '10ACCC' filter_value from dual union all
    select 102 profile_id , 50 filter_key , '10ACCC0001' filter_value from dual union all
    select 102 profile_id , 60 filter_key , 'PIP' filter_value from dual union all
    select 102 profile_id , 70 filter_key , 'A' filter_value from dual)
    select filter_key , wm_concat(filter_value) from profile_search group by profile_id, filter_key ;
    need to identify profile that matches input parameters
    102 is first match because it matches exactly
    101 is second match because 999 can match any value
    100 is third match KEY 70 HAS HIGHEST WEIGHT,
    KEY 60 has next highest weight and KEY 50 has next highest weight
    results required :
    profile_id : 102
    Edited by: devarade on Jan 19, 2010 8:01 PM
    Edited by: devarade on Jan 19, 2010 8:01 PM

    I assume there is a typo in your sample:
    select 101 profile_id , 50 filter_key , '10ACCC001' filter_value from dual union allshould be:
    select 101 profile_id , 50 filter_key , '10ACCC00<font color=red size=2>0</font>1' filter_value from dual union allThen:
    with input_parameters as (
                              select 10 filter_key , '10ACCC' filter_value from dual union all
                              select 50 filter_key ,'10ACCC0001' filter_value from dual union all
                              select 60 filter_key , 'PIP' filter_value from dual union all
                              select 70 filter_key , 'A' filter_value from dual
            profile_search as(
                              select 100 profile_id , 10 filter_key , '10ACCC' filter_value from dual union all
                              select 100 profile_id , 50 filter_key , '10ACCC0001' filter_value from dual union all
                              select 100 profile_id , 50 filter_key , '10ACCC0002' filter_value from dual union all
                              select 100 profile_id , 60 filter_key , '999' filter_value from dual union all
                              select 100 profile_id , 70 filter_key , '999' filter_value from dual union all
                              select 101 profile_id , 10 filter_key , '10ACCC' filter_value from dual union all
                              select 101 profile_id , 50 filter_key , '10ACCC0001' filter_value from dual union all
                              select 101 profile_id , 60 filter_key , 'PIP' filter_value from dual union all
                              select 101 profile_id , 70 filter_key , '999' filter_value from dual union all
                              select 102 profile_id , 10 filter_key , '10ACCC' filter_value from dual union all
                              select 102 profile_id , 50 filter_key , '10ACCC0001' filter_value from dual union all
                              select 102 profile_id , 60 filter_key , 'PIP' filter_value from dual union all
                              select 102 profile_id , 70 filter_key , 'A' filter_value from dual
    select  profile_id,
            sum(direct_match_cnt) || ' direct matches out of ' || (select count(*) from input_parameters) match
      from  (
             select  b.profile_id,
                     b.filter_key,
                     b.filter_value,
                     sum(case when b.filter_value = a.filter_value then 1 else 0 end) direct_match_cnt
               from  input_parameters a,
                     profile_search b
               where b.filter_key = a.filter_key
                 and (b.filter_value = a.filter_value or b.filter_value = '999')
               group by b.profile_id,
                        b.filter_key,
                        b.filter_value
            ) x
      group by profile_id
      having count(*) = (select count(*) from input_parameters)
      order by sum(direct_match_cnt) desc
    PROFILE_ID MATCH
           102 4 direct matches out of 4
           101 3 direct matches out of 4
           100 2 direct matches out of 4
    SQL> SY.

  • Disco -- Any analytical functions for comparisons

    Hi:
    I'm wondering if there are any analytical function to help me out with comparisons? Users often need to displays totals based on date ranges, and show the difference between the two totals, as well as percent change.
    For example, a workbook would show the comparison of cases and dollars, for 2002 vs. 2003. Currently, my solution for this is to create DECODE calculations based on year and type (cases or dollars), and perform the
    comparisons in separate calculations. I'd like to know if Discoverer already has a function that would handle some of this, and reduce the number of DECODES and separate calculations the users have to create...
    Thanks,
    Subramanyam
    Sr. Technical Consultant
    Oracle Direct

    Hello
    You can use the Oracle database SQL analytic function to perform comparison and window based calculations. Example: LAG, LEAD, RANK, etc...
    Please consult the Oracle 9.2 database documentation as well as Discoverer documentation for examples and syntax.
    Regards
    Discoverer Product Management

  • Need some kind of Analytical Function

    Hi Oracle experts
    I need a little help from you experts. I have a PARTY table as listed below
    The existing data
    Party key     ID_INTERNAL     EID          BID
    1          11111          123
    1          11111          321
    1          22222          321          899
    1          66666          ------          888
    New records comes
    I have to assign a party key to each record based on which attribute is matching
    Now the situation is as new records comes.
    New records comes
    ID_INTERNAL     EID          BID
    22222          555
    44444          555          
    89898          ------          888
    If I match on ID_INTERNAL I may not be able to match ID_INTERNAL 44444 and 89898 and if I match EID or BID the same situation.
    Is thera any analytical function which helps me assigning a party key to all the recoords. ALl the above records should be assigned PARTY KEY 1 only.
    Please help
    Thanks
    Rajesh

    Justin
    My main goal is to assign a party key from existing set of records to the new records which are being selected/inserted. I have to write my algoritum in such a way that the new values should match their value in existing records.
    Example
    my first new record has a value of 11111 under ID_INTERNAL and in the same record it has a value of 555 under EID attribute. so based on matching algoritum for ID INTERNAL it will be assigned existing party key 1.
    Similarly second new record has a value of 87777 under ID INTERNAL and has a value of 555 under EID and this ID INTERNAL does not exists in the target table. but the value of 555 is available under EID attribute so I have to write algoritum based on EID.
    Now the delima is my target table is as follows
    Party key PARTYID PARTYNAME
    1 11111 ITSID
    1 123 EID
    1 321 EID
    Now when new records come I have to write match algortium for ID_INTERNAL to PARTYID for Partyname='ITSID'
    Once matched this record ID INTERNAL=11111 and EID =555 assigned a party key=1. So after first record the output table slooks like
    Party key PARTYID PARTYNAME
    1 11111 ITSID
    1 123 EID
    1 321 EID
    1 555 EID
    Same way for second new record where the values are ID_INTERNAL=87777 and EID=555. I have to write match algortium based on EID because the EID value of 555 already exists in target tabel with party key.
    SO after second record the target table will look like
    Party key PARTYID PARTYNAME
    1 11111 ITSID
    1 123 EID
    1 321 EID
    1 555 EID
    1 87777 ITSID
    So this is how I have to solve this match algoritum.
    Please help me if you need any information I will be glad to provide you all.
    Thanks
    Regards
    Rajesh

  • Help with analytical function

    I successfully use the following analytical function to sum all net_movement of a position (key for a position: bp_id, prtfl_num, instrmnt_id, cost_prc_crncy) from first occurrence until current row:
    SELECT SUM (net_movement) OVER (PARTITION BY bp_id, prtfl_num, instrmnt_id, cost_prc_crncy ORDER BY TRUNC (val_dt) RANGE BETWEEN UNBOUNDED PRECEDING AND 0 FOLLOWING) holding,
    what i need is another column to sum net_movement of a position but only for the current date, but all my approaches fail..
    - add the date (val_dt) to the 'partition by' clause and therefore sum only values with same position and date
    SELECT SUM (net_movement) OVER (PARTITION BY val_dt, bp_id, prtfl_num, instrmnt_id, cost_prc_crncy ORDER BY TRUNC (val_dt) RANGE BETWEEN UNBOUNDED PRECEDING AND 0 FOLLOWING) today_net_movement
    - take the holding for the last date and subtract it from the current holding afterwards
    SELECT SUM (net_movement) OVER (PARTITION BY bp_id, prtfl_num, instrmnt_id, cost_prc_crncy ORDER BY TRUNC (val_dt) RANGE BETWEEN UNBOUNDED PRECEDING AND -1 FOLLOWING) last_holding,
    - using lag on the analytical function which calculates holding fails too
    I also want to avoid creating a table which stores the last holding..
    Does anyone sees where I make a mistake or knows an alternative to get this value?
    It would help me much!
    Thanks in advance!

    Thank you,
    but I already tried that but it returns strange values which are not the correct ones for sure.
    It is always the same value for each row, if its not 0, and a very high one (500500 for example), even if the sum of all net_movement of that date is 0 (and the statement for holding returns 0 too)
    I also tried witch trunc(val_dt,'DDD') with the same result (without trunc it is the same issue)
    please help if you can, thanks in advance!

  • Help on Using Analytical Functions

    I am hetting error when i use Analytical functions in Expressions
    AVG( INGRP1.Test1 ) OVER (PARTITION BY INGRP1.Test2)
    Error is as follows
    Line 1, Col 28:
    PLS-00103: Encountered the symbol "OVER" when expecting one of the following:
    * & = - + ; < / > at in is mod remainder not rem
    <an exponent (**)> <> or != or ~= >= <= <> and or like LIKE2_
    LIKE4_ LIKEC_ between || multiset member SUBMULTISET_

    Hi,
    the syntax of this part of the sql statement is okay. Please post the complete statement to identify the error.
    Sometimes oracle identifies the wrong point for the error.
    Regards,
    Detlef

  • I need help with Analytic Function

    Hi,
    I have this little problem that I need help with.
    My datafile has thousands of records that look like...
    Client_Id Region Countries
    [1] [1] [USA, Canada]
    [1] [2] [Australia, France, Germany]
    [1] [3] [China, India, Korea]
    [1] [4] [Brazil, Mexico]
    [8] [1] [USA, Canada]
    [9] [1] [USA, Canada]
    [9] [4] [Argentina, Brazil]
    [13] [1] [USA, Canada]
    [15] [1] [USA]
    [15] [4] [Argentina, Brazil]
    etc
    My task is is to create a report with 2 columns - Client_Id and Countries, to look something like...
    Client_Id Countries
    [1] [USA, Canada, Australia, France, Germany, China, India, Korea, Brazil, Mexico]
    [8] [USA, Canada]
    [9] [USA, Canada, Argentina, Brazil]
    [13] [USA, Canada]
    [15] [USA, Argentina, Brazil]
    etc.
    How can I achieve this using Analytic Function(s)?
    Thanks.
    BDF

    Hi,
    That's called String Aggregation , and the following site shows many ways to do it:
    http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
    Which one should you use? That depends on which version of Oracle you're using, and your exact requirements.
    For example, is order importatn? You said the results shoudl include:
    CLIENT_ID  COUNTRIES
    1        USA, Canada, Australia, France, Germany, China, India, Korea, Brazil, Mexicobut would you be equally happy with
    CLIENT_ID  COUNTRIES
    1        Australia, France, Germany, China, India, Korea, Brazil, Mexico, USA, Canadaor
    CLIENT_ID  COUNTRIES
    1        Australia, France, Germany, USA, Canada, Brazil, Mexico, China, India, Korea?
    Mwalimu wrote:
    ... How can I achieve this using Analytic Function(s)?The best solution may not involve analytic functions at all. Is that okay?
    If you'd like help, post your best attempt, a little sample data (CREATE TABLE and INSERT statements), the results you want from that data, and an explanation of how you get those results from that data.
    Always say which version of Oracle you're using.
    Edited by: Frank Kulash on Aug 29, 2011 3:05 PM

  • About FIRST_ROW analytic function; can anyone help?

    Hi everyone,
    Can anyone help me with this simple query?
    Let's suppose I have this query (the with clause contains some data):
    WITH T AS (
    SELECT 'TEST' as COL1, 1 as COL2, 'z' as COL3 FROM dual
    UNION ALL
    SELECT 'TEST', 2, 'y' FROM dual
    UNION ALL
    SELECT 'TEST', 2, 'h' FROM dual
    SELECT FIRST_VALUE(COL1) OVER (PARTITION BY COL1), COL2, COL3
      FROM T;I would like to have only the first row returned. I was thinking that with FIRST_VALUE it will be possible, but it returns 3 records.
    So can anyone help me to have only the first record returned?
    TEST     1     zThis is just a simple example. In reality I have thousands of records. I need to get only the first record based on the name (TEST in this example). We don't really care about the other columns.
    Thanks for your help,

    user13117585 wrote:
    I would like to have only the first row returned. I was thinking that with FIRST_VALUE it will be possible, but it returns 3 records. Analytic functions don't filter rows, they just calculate values from some part of the result set.
    Aggregating is the most efficient way of doing this query:
    SQL> WITH T AS (
      2  SELECT 'TEST' as COL1, 1 as COL2, 'z' as COL3 FROM dual
      3  UNION ALL
      4  SELECT 'TEST', 2, 'y' FROM dual
      5  UNION ALL
      6  SELECT 'TEST', 2, 'h' FROM dual
      7  )
      8  select col1
      9       , min(col2) col2
    10       , max(col3) keep (dense_rank first order by col2) col3
    11    from t
    12   group by col1
    13  /
    COL1       COL2 C
    TEST          1 z
    1 row selected.Regards,
    Rob.

  • Help with Oracle Analytic Function scenario

    Hi,
    I am new to analytic functions and was wondering if someone could help me with the data scenario below. I have a table with the following data
    COLUMN A COLUMN B COLUMN C
    13368834 34323021 100
    13368835 34438258 50
    13368834 34438258 50
    13368835 34323021 100
    The output I want is
    COLUMN A COLUMN B COLUMN C
    13368834 34323021 100
    13368835 34438258 50
    A simple DISTINCT won't give me the desired output so i was wondering if there is any way that I can get the result using ANALYTIC FUNCTIONS and DISTINCT ..
    Any help will be greatly appreciated.
    Thanks.

    Hi,
    Welcome to the forum!
    Whenever you have a question, please post your sample data in a form that people can use to re-create the problem and test their solutions.
    For example:
    CREATE TABLE     table_x
    (      columna     NUMBER
    ,      columnb     NUMBER
    ,      columnc     NUMBER
    INSERT INTO table_x (columna, columnb, columnc) VALUES (13368834, 34323021, 100);
    INSERT INTO table_x (columna, columnb, columnc) VALUES (13368835, 34438258, 50);
    INSERT INTO table_x (columna, columnb, columnc) VALUES (13368834, 34438258, 50);
    INSERT INTO table_x (columna, columnb, columnc) VALUES (13368835, 34323021, 100);Do you want something that works in your version or Oracle? Of course you do! So tell us which version that is.
    How do you get the results that you want? Explain what each row of output represents. It looks like
    the 1st row contains the 1st distinct value from each column (where "first" means descending order for columnc, and ascending order for the others),
    the 2nd row contains the 2nd distinct value,
    the 3rd row contains the 3rd distinct value, and so on.
    If that's what you want, here's one way to get it (in Oracle 9 and up):
    WITH     got_nums     AS
         SELECT     columna, columnb, columnc
         ,     DENSE_RANK () OVER (ORDER BY  columna        )     AS a_num
         ,     DENSE_RANK () OVER (ORDER BY  columnb        )     AS b_num
         ,     DENSE_RANK () OVER (ORDER BY  columnc  DESC)     AS c_num
         FROM     table_x
    SELECT       MAX (a.columna)          AS columna
    ,       MAX (b.columnb)          AS columnb
    ,       MAX (c.columnc)          AS columnc
    FROM              got_nums     a
    FULL OUTER JOIN  got_nums     b     ON     b.b_num     =           a.a_num
    FULL OUTER JOIN  got_nums     c     ON     c.c_num     = COALESCE (a.a_num, b.b_num)
    GROUP BY  COALESCE (a.a_num, b.b_num, c.c_num)
    ORDER BY  COALESCE (a.a_num, b.b_num, c.c_num)
    ;I've been trying to find a good name for this type of query. The best I've heard so far is "Prix Fixe Query", named after the menus where you get a choice of soups (listed in one column), appetizers (in another column), main dishes (in a 3rd column), and so on. The items on the first row don't necessaily have any relationship to each other.
    The solution does not assume that there are the same number of distinct items in each column.
    For example, if you add this row to the sample data:
    INSERT INTO table_x (columna, columnb, columnc) VALUES (13368835, 34323021, 99);which is a copy of the last row, except that there is a completely new value for columnc, then the output is:
    `  COLUMNA    COLUMNB    COLUMNC
      13368834   34323021        100
      13368835   34438258         99
                                  50starting in Oracle 11, you can also do this with an unpivot-pivot query.

  • Does sql analytic function help to determine continuity in occurences

    We need to solve this problem in a sql statement.
    imagine a table test with two columns
    create table test (id char(1), begin number, end number);
    and these values
    insert into test('a',1, 2);
    insert into test('a',2,3);
    insert into test('a',3,4);
    insert into test('a',7,10);
    insert into test('a',10,15);
    insert into test('b',5,9);
    insert into test('b',9,21);
    insert into test('c',1,5);
    our goal is to determine continuity in number sequence between begin and end attributes for a same id and determine min and max number from these contuinity chains.
    The result may be
    a, 1, 4
    a, 7, 15
    b, 5, 21
    c, 1, 5
    We test some analytic functions like lag, lead, row_number, min, max, partition by, etc to search a way to identify row set that represent a continuity but we didn't find a way to identify (mark) them so we can use min and max functions to extract extreme values.
    Any idea is really welcome !

    Here is our implementation in a real context for example:
    insert into requesterstage(requesterstage_i, requester_i, t_requesterstage_i, datefrom, dateto )
    With ListToAdd as
    (Select distinct support.requester_i,
    support.datefrom,
    support.dateto
    from support
    where support.datefrom < to_date('01.01.2006', 'dd.mm.yyyy')
    and support.t_relief_i = t_relief_ipar.fgetflextypologyclassitem_i(t_relief_ipar.fismedicalexpenses)
    and not exists
    (select null
    from requesterstage
    where requesterstage.requester_i = support.requester_i
    and support.datefrom < nvl(requesterstage.dateto, support.datefrom + 1)
    and nvl(support.dateto, requesterstage.datefrom + 1) > requesterstage.datefrom)
    ListToAddAnalyzed_1 as
    (select requester_i,
    datefrom,
    dateto,
    decode(datefrom,lag(dateto) over (partition by requester_i order by datefrom),0,1) data_set_start
    from ListToAdd),
    ListToAddAnalyzed_2 as
    (select requester_i,
    datefrom,
    dateto,
    data_set_start,
    sum(data_set_start) over(order by requester_i, datefrom ) data_set_id
    from ListToAddAnalyzed_1)
    select requesterstage_iseq.nextval,
    requester_i,
    t_requesterstage_ipar.fgetflextypologyclassitem_i(t_requesterstage_ipar.fisbefore2006),
    datefrom,
    decode(sign(nvl(dateto, to_date('01.01.2006', 'dd.mm.yyyy')) -to_date('01.01.2006', 'dd.mm.yyyy')), 0, to_date('01.01.2006', 'dd.mm.yyyy'), -1, dateto, 1, to_date('01.01.2006', 'dd.mm.yyyy'))
    from ( select requester_i
    , min(datefrom) datefrom
    , max(dateto) dateto
    From ListToAddAnalyzed_2
    group by requester_i, data_set_id
    );

  • Help needed with analytical function

    I want to get the employee details of the highest and 2nd highest salaried employee in a particular department. But also the department should have more than 1 employee.
    I tried the query and it gave me proper results. But I'm wondering if there is some other alternative than using the subquery.
    Here is the table and the result query :
    with t as
    select 1 emp_id,3 mgr_id,'Rajesh' emp_name,3999 salary,677 bonus,'HR' dpt_nme from dual union
    select 2 ,3 ,'Gangz',4500,800,'Finance' from dual  union
    select 3 ,4 ,'Sid',8000,12000,'IT' from dual  union
    select 4 ,null,'Ram',5000,677,'HR' from dual  union
    select 5 ,4,'Shyam',6000,677,'IT' from dual union
    select 6 ,4 ,'Ravi',9000,12000,'IT' from dual  
    select * from
    (select emp_id, mgr_id, emp_name, dpt_nme, salary, row_number() over (partition by dpt_nme order by salary desc) rn from t where dpt_nme in
    (select dpt_nme from t group by dpt_nme having count(*) > 1)) where rn < 3

    Hi,
    You need a sub-query, but you don't need more than that.
    Here's one way to eliminate the extra sub-query:
    WITH     got_analytics     AS
         SELECT  emp_id,     mgr_id,     emp_name, dpt_nme, salary
         ,     ROW_NUMBER () OVER ( PARTITION BY  dpt_nme
                                   ORDER BY          salary     DESC
                           )         AS rn
         ,     COUNT (*)     OVER ( PARTITION BY  dpt_nme
                                       )         AS dpt_cnt
         FROM     t
    SELECT  emp_id,     mgr_id,     emp_name, dpt_nme, salary
    ,     rn
    FROM     got_analytics
    WHERE     rn     < 3
    AND     dpt_cnt     > 1
    ;Analytic functions are computed after the WHERE clause is applied. Since we need to use the results of the analytic ROW_NUMBER function in a WHERE clause, that means we'll have to compute ROW_NUMBER in a sub-query, and use the results in the WHERE clause of the main query. We can call the analytic COUNT function in the same sub-query, and use its results in the same WHERE clause of the main query.
    What results would you want if there's a tie for the 2nd highest salary in some department? For example, if you add this row to your sample data:
    select 7 ,3 ,'Sunil',8000,12000,'IT' from dual  union? You may want to use RANK instead of ROW_NUMBER.

  • Help with analytical function   (ora 9...)

    Hi everyone, is there a way to fill some missing numbers based on what have come before and after that missing number by starttime and based on how many missing data are between? ... by "simple" select? I know how to do that just theoreticly with simple math commands, but is there a way to apply them in sql (analytical functions)?
    Thanks in advance for any ideas !
    The missing number on line 17 could be calculated as 339+(1/2)*(356-339) = 347,5
    The missing number on line 23 could be calculated as 355+(1/3)*(292-355) = 334
    The missing number on line 24 could be calculated as 355+(2/3)*(292-355) = 313
    rownumber + temp_table (starttime,data_column)
    15     23.5.2007 16:15     ,     258
    16     23.5.2007 16:30     ,     339
    17     23.5.2007 16:45     ,     
    18     23.5.2007 17:00     ,     356
    19     23.5.2007 17:15     ,     373
    20     23.5.2007 17:30     ,     355
    21     23.5.2007 17:45     ,     363
    22     23.5.2007 18:00     ,     355
    23     23.5.2007 18:15     ,     
    24     23.5.2007 18:30     ,     
    25     23.5.2007 19:00     ,     292
    26     23.5.2007 19:15     ,     295
    THANKS
    Message was edited by:
    dusoo

    Way too late, but I wouldn't let my effort go unpublished ;-)
    SQL> create table temp_table
      2  as
      3  select 15 rownumber, to_date('23.5.2007 16:15','dd.mm.yyyy hh24:mi') starttime, 258 data_column from dual union all
      4  select 16, to_date(' 23.5.2007 16:30','dd.mm.yyyy hh24:mi'), 339 from dual union all
      5  select 17, to_date(' 23.5.2007 16:45','dd.mm.yyyy hh24:mi'), null from dual union all
      6  select 18, to_date(' 23.5.2007 17:00','dd.mm.yyyy hh24:mi'), 356 from dual union all
      7  select 19, to_date(' 23.5.2007 17:15','dd.mm.yyyy hh24:mi'), 373 from dual union all
      8  select 20, to_date(' 23.5.2007 17:30','dd.mm.yyyy hh24:mi'), 355 from dual union all
      9  select 21, to_date(' 23.5.2007 17:45','dd.mm.yyyy hh24:mi'), 363 from dual union all
    10  select 22, to_date(' 23.5.2007 18:00','dd.mm.yyyy hh24:mi'), 355 from dual union all
    11  select 23, to_date(' 23.5.2007 18:15','dd.mm.yyyy hh24:mi'), null from dual union all
    12  select 24, to_date(' 23.5.2007 18:30','dd.mm.yyyy hh24:mi'), null from dual union all
    13  select 25, to_date(' 23.5.2007 19:00','dd.mm.yyyy hh24:mi'), 292 from dual union all
    14  select 26, to_date(' 23.5.2007 19:15','dd.mm.yyyy hh24:mi'), 295 from dual
    15  /
    Tabel is aangemaakt.
    SQL> with t as
      2  ( select t.*
      3         , max(case when data_column is not null then rownumber end) over (order by rownumber) lowerbound
      4         , last_value(data_column ignore nulls) over (order by rownumber) prevvalue
      5         , min(case when data_column is not null then rownumber end) over (order by rownumber desc) upperbound
      6         , last_value(data_column ignore nulls) over (order by rownumber desc) nextvalue
      7      from temp_table t
      8  )
      9  select rownumber
    10       , starttime
    11       , case
    12         when data_column is not null then data_column
    13         else   prevvalue * ((upperbound - rownumber) / (upperbound - lowerbound))
    14              + nextvalue * ((rownumber - lowerbound) / (upperbound - lowerbound))
    15         end data_column
    16    from t
    17   order by rownumber
    18  /
                                 ROWNUMBER STARTTIME                                      DATA_COLUMN
                                        15 23-05-2007 16:15:00                                    258
                                        16 23-05-2007 16:30:00                                    339
                                        17 23-05-2007 16:45:00                                  347,5
                                        18 23-05-2007 17:00:00                                    356
                                        19 23-05-2007 17:15:00                                    373
                                        20 23-05-2007 17:30:00                                    355
                                        21 23-05-2007 17:45:00                                    363
                                        22 23-05-2007 18:00:00                                    355
                                        23 23-05-2007 18:15:00                                    334
                                        24 23-05-2007 18:30:00                                    313
                                        25 23-05-2007 19:00:00                                    292
                                        26 23-05-2007 19:15:00                                    295
    12 rijen zijn geselecteerd.Regards,
    Rob.

Maybe you are looking for

  • Problems with FCP 5.1.4 and OSX 10.4.9

    I upgraded to Tiger, installed the new FCP Studio and everything was working fantastic. The next morning there was a software update for Tiger and FCP-5.1.4, it's been a nightmare ever since. When I restarted FCP would not recognize my Sony HDR FX1.

  • ALV Report - Production Scheduling Report

    Hello Gurus, I need to write an ALV report of open production order operations per selection criteria.  If the production orders are linked to any sales order, then the result of ALV should also contain the sales order data. Selection screen should c

  • Nokia 6500c Problem!

    my nokia 6500c doesn't seem to be getting any signal at all! i turn the phone on and i get signal for like 2 mins and then it just keep saying '' sim card registration failed '' or '' check info service '', does anyone know how to fix this thanks in

  • Agents handling multiple IVR/Call center calls

    The scenario is that you have  agents who have multiple skill sets and can take calls from 2 different IVR/Call centers. Now you want to assign calls from IVR1 a higher priority over calls from IVR2. Can that be done in ICM since the calls are coming

  • Is it possible using the JTA

    Hi I am new to JTA and have a question.. Is JTA used only for handling transactions in Database and can it be used for other purposes like rolling back a method or revert a state of an object in the program. I have a situation where i have to ftp som