Group records in a Select statement

I want to know, if I can do this with a single select:

I have a table where I have some information with a collar-date:
Column1  Column2  Column3  DateCol
-------
A        B        C        10/2001
A        B        C        03/2001
B        B        C        02/2001
B        B        C        01/2001
A        B        C        03/2000
Now, I want to bring together the combination of col1-3, but in chronological order. This should be the result:
Column1  Column2  Column3  DateCol
-------
A        B        C        10/2001
B        B        C        02/2001
A        B        C        03/2000
Any ideas?

Rumburak wrote:
It is not a simple question group. Look at my example. The DateCol is the validity of a combination.

If this is not a simple GROUP BY, then what is? Please explain what you are trying to do.
That means each line of output represent?
Why do you want 3 production lines and not 1 or 2, or 4 or 5?
Why some production lines have distinct values in col1, col2 and col3, and others do not?

It is possible that you wanted something like this:

WITH     got_nums     AS
(
     SELECT     col1, col2, col3
     ,     datecol
     ,     ROW_NUMBER () OVER ( PARTITION BY  col1, col2, col3
                               ORDER BY          datecol
                       )                    AS group_num
     ,     ROW_NUMBER () OVER ( ORDER BY      datecol)     AS overall_num
     FROM     tbl
)
SELECT       col1, col2, col3
,       TO_CHAR ( MAX (datecol)
              , 'MM/YYYY'
            )          AS datecol_month_year
FROM       got_nums
GROUP BY  col1, col2, col3
,            overall_num - group_num
ORDER BY  MAX (datecol)               DESC
;

but at least I understand the problem, I can only guess. Guess, this isn't a very effective way to work.

Tags: Database

Similar Questions

  • Need help with the use of GROUP BY in a select statement UNION

    I am writing a query that allows to combine a legacy system that interfaces it is trial balance in the Oracle of R12 GL.  It was only meant to continue for a month or two, but it is likely to continue for 6 months. Please Auditors Auditors, to provide proof that the system is in balance with Oracle GL.  By my verification requirements, I need to make a full reconciliation from the month of conversion (life in the amount of date), then PTD for each month. 

    The legacy account is placed in attribute1 on the lines of the journals. Uses of the old system balancing segments that are also used on the platform in Oracle for this division, i.e., Procure-to-Pay has been cut over Oracle, but not everything yet.  So, I can't count on the GL_BALANCES table for the info, I get from the JE_LINES.

    My problem is not the only request for the month.  But when I try to combine the queries with a Union, to aggregation of each measurement period in its own column, the group is necessary after each selected instruction rather than allowing me to put at the end of the UNION.  (When I put the group by at the end of the UNION, I have the 'not one group' function)

    So I get duplicate for each month of discrete measure accounts. When I duplicate in my Oracle database accounts, I can't count on the VLOOKUP function in excel to exactly match an account of inheritance.  I know there are more sophisticated ways to provide this output, but I'm hoping to get this info in a simple query.

    Thank you in advance for any advice you can provide

    Example of data output (the goal for me is to get the two rows to appear as one based on common points on the LEGACY_ACCOUNT and the ORACLE ACCOUNT

    The LEGACY ACCOUNT ORACLE ACCOUNT JUN_15 JUL_15 AUG_15 SEP_15 OCT_15 NOV_15 DEC_15
    010000001109000003584190-600552-1001-100231-000-0000-0000-000000-242961.040000
    010000001109000003584190-600552-1001-100231-000-0000-0000-00000192588.0200000

    Here is a simplified version of my code that returns both records.  In my research, I had found a number of conversations where it has been shown that the group could be put at the end of the select statement.  However, when I remove the group from the first select statement I get SQL error: ORA-00937: not a function of simple-group

    Select

    l.attribute1 LEGACY_ACCOUNT,

    C.SEGMENT1: '-' | C.SEGMENT2: '-' | C.SEGMENT3: '-' | C.SEGMENT4: '-' | C.SEGMENT5: '-' | C.SEGMENT6: '-' | C.SEGMENT7: '-' | COMBINATION OF C.SEGMENT8,

    JUN_15 TO_NUMBER('0').

    JUL_15, sum (NVL(l.accounted_dr,0.00)-NVL(l.accounted_cr,0.00)),

    TO_NUMBER('0') AUG_15.

    TO_NUMBER('0') SEP_15.

    TO_NUMBER('0') OCT_15.

    TO_NUMBER('0') NOV_15.

    DEC_15 TO_NUMBER('0')

    Of

    b GL.gl_je_batches,

    GL.gl_je_headers h,

    GL.gl_je_lines l,

    GL.gl_code_combinations c,

    GL.gl_je_sources_tl j

    where b.je_batch_id = h.je_batch_id

    and h.je_header_id = l.je_header_id

    and l.code_combination_id = c.code_combination_id

    and h.je_source = j.je_source_name

    and c.segment1 ('190 ', '191', '192', '193', '194', ' 195 ', ' 196',' 197', ' 198 ', ' 199',)

    ('200 ', '203', ' 205', '206 ', '330', '331', '332',' 333 ', ' 334',' 335', ' 336 ', ' 337')

    and j.language = 'en '.

    and h.PERIOD_NAME ("JUL-15'")

    Group

    l.attribute1,

    C.SEGMENT1: '-' | C.SEGMENT2: '-' | C.SEGMENT3: '-' | C.SEGMENT4: '-' | C.SEGMENT5: '-' | C.SEGMENT6: '-' | C.SEGMENT7: '-' | C.SEGMENT8

    UNION

    Select

    l.attribute1 LEGACY_ACCOUNT,

    C.SEGMENT1: '-' | C.SEGMENT2: '-' | C.SEGMENT3: '-' | C.SEGMENT4: '-' | C.SEGMENT5: '-' | C.SEGMENT6: '-' | C.SEGMENT7: '-' | COMBINATION OF C.SEGMENT8,

    JUN_15 TO_NUMBER('0').

    TO_NUMBER('0') JUL_15.

    AUG_15, sum (NVL(l.accounted_dr,0.00)-NVL(l.accounted_cr,0.00)),

    TO_NUMBER('0') SEP_15.

    TO_NUMBER('0') OCT_15.

    TO_NUMBER('0') NOV_15.

    DEC_15 TO_NUMBER('0')

    Of

    b GL.gl_je_batches,

    GL.gl_je_headers h,

    GL.gl_je_lines l,

    GL.gl_code_combinations c,

    GL.gl_je_sources_tl j

    where b.je_batch_id = h.je_batch_id

    and h.je_header_id = l.je_header_id

    and l.code_combination_id = c.code_combination_id

    and h.je_source = j.je_source_name

    and c.segment1 ('190 ', '191', '192', '193', '194', ' 195 ', ' 196',' 197', ' 198 ', ' 199',)

    ('200 ', '203', ' 205', '206 ', '330', '331', '332',' 333 ', ' 334',' 335', ' 336 ', ' 337')

    and j.language = 'en '.

    and h.PERIOD_NAME ("AUG-15'")

    Group

    l.attribute1,

    C.SEGMENT1: '-' | C.SEGMENT2: '-' | C.SEGMENT3: '-' | C.SEGMENT4: '-' | C.SEGMENT5: '-' | C.SEGMENT6: '-' | C.SEGMENT7: '-' | C.SEGMENT8

    order by 1

    Is there a good reason to make this period both as a series of trade unions?  This looks like a classic pivot for me query.  This will make a way through the tables and should get the desired results.

    Select l.attribute1 legacy_account,

    c.Segment1: '-' | c.Segment2: '-' | c.segment3: '-' | c.segment4: '-' |

    c.segment5: '-' | c.segment6: '-' | c.segment7: '-' | combination of c.segment8,

    sum (case when h.period_name = 'JUN-15'

    then nvl(l.accounted_dr,0.00)-nvl(l.accounted_cr,0.00)

    otherwise 0 end) jun_15,.

    sum (case when h.period_name = 'JUL-15'

    then nvl(l.accounted_dr,0.00)-nvl(l.accounted_cr,0.00)

    otherwise 0 end) jul_15,.

    - and similar to DEC - 15

    GL.gl_je_batches b, gl.gl_je_headers h, gl.gl_je_lines l.

    GL.gl_code_combinations c, gl.gl_je_sources_tl j

    where b.je_batch_id = h.je_batch_id

    and h.je_header_id = l.je_header_id

    and l.code_combination_id = c.code_combination_id

    and h.je_source = j.je_source_name

    and c.segment1 ('190', '191', '192', '193', '194', '195',' 196', ' 197',

    '198 ', '199', '200', '203', '205' ', 206',' 330 ', ' 331',

    "332 ', '333', '334', '335',' 336 ', ' 337')

    and j.language = 'en '.

    and h.period_name (' Jun-15', ' 15 JUL', ' AUG-15'... "" ")

    L.attribute1 group,

    c.Segment1: '-' | c.Segment2: '-' | c.segment3: '-' |

    c.segment4: '-' | c.segment5: '-' | c.segment6: '-' |

    c.segment7: '-' | c.segment8

    If you're on the 11G version of the database, you might want to look at the PIVOT keyword that will do the same thing in a more concise expression.

    John

  • Skip and capture the Oracle SQL record dirty in a select statement

    Hello

    I have the Oracle Oracle 11.2.0.4 database when I run a select query.

    Question:

    10 columns have given Date format. When I try to execute this query into a FROG he says, a month not valid. Since the records are billion in nature, I am not able to know which line has this problem.

    Is there a way I can capture the failed row and add it to other tables and continues with the select statement regardless of this error

    OK, you have several TO_DATE functions fed a string that is built on the fly.  At least part of the time, the chain that is built does not match the date format mask used.

    For example:

    TO_DATE (SUBSTR (TO_CHAR (SQ_W_PURCH_CYCLNS_ORA. LAST_SUBMITTED_ON_DTTM_WID), 0, 8). » -'|| SUBSTR (TO_CHAR (SQ_W_PURCH_CYCLNS_ORA. (LAST_SUBMITTED_ON_DTTM_WID), 9, 6), "YYYYMMDD-HH24MISS")

    "SQ_W_PURCH_CYCLNS_ORA. LAST_SUBMITTED_ON_DTTM_WID' does not have a string where characters 5-6 are in the range 01-12.  You'll have to do an analysis on this column.  From its data and how that is managed by to_char.  What ARE the data type of ' SQ_W_PURCH_CYCLNS_ORA. LAST_SUBMITTED_ON_DTTM_WID' and what is a typical value?

    As others have said, this is simply an impossibility for a column of a table to actually have invalid month (or day, or year, or hour or minute or second).  ONLY, you get this error during the conversion of a string to a date with the TO_DATE function.

  • How to INSERT a SELECT statement with a GROUP BY clause on a table with an IDENTITY column?

    n an application, I intend to truncate and insertion on a 12 c Oracle database, but have found this problem with a IDENTITY column. Even if the INSERT... SELECT statement works on most SELECT uses I tried, if this statement was also a GROUP BY clause, it does not work, delivering a "ORA-00979: not a GROUP BY expression ' complaint. Some examples of code:

    create table aux ( owner_name varchar2(20), pet varchar2(20) ); 

    insert into aux values ('Scott', 'dog');

    insert into aux values ('Mike', 'dog');

    insert into aux values ('Mike', 'cat');

    insert into aux values ('John', 'turtle'); 


    create table T1 (

    id number generated always as identity,

    owner_name varchar2(20),

    pet_count number );

    select owner_name, count(*) as pet_count from aux group by owner_name; -- works just fine

    insert into T1 (owner_name, pet_count) select owner_name, count(*) as pet_count from aux group by owner_name; -- doesn't work

    The select statement works by itself, but it fails as an INSERT... SELECT statement.

    Appreciate the help!

    Looks like a bug. You must open the SR with Oracle. Meanwhile, you could materialize select:

    SQL > insert into T1 (owner_name, pet_count)
    2 with t as (select / * + materialize * / owner_name, count (*) as pet_count to the owner_name group)
    3. Select owner_name, pet_count t
    4.

    3 lines were created.

    SQL > select * from t1;

    ID OWNER_NAME PET_COUNT
    ---------- -------------------- ----------
    1 John                          1
    Scott 2 1
    3 Mike                          2

    SQL >

    Keep in mind index THAT MATERIALIZE is undocumented.

    SY.

  • validation for each 1,000 records to be inserted in the select statement

    Hi, I have the following INSERTION in the SELECT statement.
    The SELECT statement (who joined) data fo about 6 crores. I need to insert this data into another table.

    Please suggest me the best way to do it.
    I use the INSERT in the SELECT statement, but I want to use the statement commit for each 1,000 records.

    How can I do this...
    insert into emp_dept_master 
     select e.ename ,d.dname ,e.empno ,e.empno ,e.sal 
       from emp e , dept d
      where e.deptno = d.deptno       ------ how to use commit for every 1000 records .
    Thank you

    Method 4 is the best

    You could combine method 3 and 1 (without dynamic SQL)

    Method 2 is the less optimal solution from the list.

  • Is it possible to use the record type or a PL/SQL table in the Select statement

    Hi all

    My requirement is that.
    I want to write a query and write a function, function, I want to return multiple columns at the same time in a Select statement.
    I select the return values in the Select no statement in a PL/SQL block.
    Is it possible to use the PL/SQL Table or Variable of Type record, or any other method in the statement Select?

    Please help me understand the solution.


    Kind regards

    830960 wrote:
    do we like it?

    In general, Yes, if the function is a function table, you can do something like:

    select  t.col1,
            t.col2,
            f.col1,
            f.col2,
            f.col3
      from  table_name t,
               table(some_table_function(param1,...paramN)) f
    /
    

    SY.

  • to find the number of records retrieved in the select statement in the cursor

    Hi all
    with the cursor, I'm selecting select statement together and writing in the .txt file.
    his worksheet, but it should not open the file, if the cursor returns nothing.
    How to find the number of records returned by the select statement in the cursor.
    pls help me.

    Thank you...

    Don't understand what you're trying to say, but maybe it's...

    DECLARE
       vCounter NUMBER;
       -- Other variables...
    BEGIN
       vCounter:=0;
       FOR .. IN cursor LOOP
        IF vCounter=0 THEN
          -- Here open file...
          -- Here write one time data...
        END IF;
        -- Here write cursor data...
        vCounter:=1;
       END LOOP;
    END;
    

    -Clément

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

  • SQL select statements

    Hey everybody,

    First of all, Yes, I searched through the 8.5 database schema guide.  As I went through the scheme, I've developed some ideas on how to collect the data you want.  However, if someone has already developed or found the SQL statements (which I'm sure that someone already has) it would help by reducing to the minimum of the buggs in my data collection program.

    All these statistics must be grouped by CSQ and selected for a certain time interval ( and ).  That is, levels of 1 hour.  I have no problem to get a list of results and then perform v.f. to achieve the desired final result.  Also, if I need to run several select statements for tables of essentially two join, please include two statements.  Finally, I saw the RtCSQsSummary table, but I need to collect data for the past, not at this time.

    1 total calls presented by the CSQ

    2. total number of calls answered by the CSQ

    3 total number of calls abandoned by the CSQ

    4. percentage of calls abandoned by CSQ (if it is not stored in the database, I think: /)

    5. average abandon time in seconds (if it is not stored in the DB, I think: sum () /)

    6. service level - % calls answered in 90 seonds by a set of skills (I have seen metServiceLevel in the ContactQueueDetail table; however, I need to find how to configure this threshold for application)

    7. average speed of response by CSQ

    8 average conversation by CSQ calls

    9. the aggregates connected full-time resources or agents CSQ

    10. resources/agents of CSQ ready time

    I realize that some of them should be easy to find (as I always am search in the guide of db schema), but I was reading how a new record is created for each step of the call so I could easily see how I could get inaccurate information without properly developed select statements.

    Any help will be greatly appreciated.

    Brendan

    Brendan,

    I read your message very well.

    You have the schema of database with tables and description. each table has its associated tables (connected with primary and foreign keys). I think you should start the tables to determine what you need.

    Cisco uses the stored procedure to prepare the reports. the stored procedure is 'sp_csq_interval' to create the report.

    Activity report of Queue Service contact"

    HTH

    Anas

    Please note all useful posts

  • Group records as well as frequent mailers

    Hi people,

    I'm looking at a scenario where I would like to group the dates together (for the most part, we assume they are similar and close enough dates and so probably on the same date) when they are close together. The idea is to eliminate the possible duplicates.

    Create table scripts and INSERT into the table:

    create table orders_tb (order_id varchar2(4), order_date date);
    
    insert into orders_tb (order_id,order_date) values ('1001',to_date('31-DEC-13','DD-MON-RR'));
    insert into orders_tb (order_id,order_date) values ('1001',to_date('02-JAN-14','DD-MON-RR'));
    insert into orders_tb (order_id,order_date) values ('1001',to_date('06-JAN-14','DD-MON-RR'));
    insert into orders_tb (order_id,order_date) values ('1001',to_date('12-JAN-14','DD-MON-RR'));
    insert into orders_tb (order_id,order_date) values ('1002',to_date('02-FEB-14','DD-MON-RR'));
    insert into orders_tb (order_id,order_date) values ('1002',to_date('02-MAR-14','DD-MON-RR'));
    insert into orders_tb (order_id,order_date) values ('1002',to_date('02-MAR-14','DD-MON-RR'));
    

    If I ran the following SELECT statement, I would get 6 entries:

    select distinct order_id, order_date from orders_tb order by order_id, order_date;
    

    However, for the most part, I would like to Order ID 1001 subject only two records. The rule for including dates, that is all the dates to be within 10 days of the date of MIN.

    1001 31-DEC-2013
    1001 12-JAN-2014
    

    Regarding the command ID 1002, he will tell you that the dates are very far.

    1002 02-FEB-2014
    1002 02-MAR-2014
    

    Any help would be greatly appreciated.

    Thank you!

    Hello

    You want to always 2 rows for each order_id exit or you want sometimes 1 or 3 or more?

    You can test it with a little more data sample that test situations like these.  For example, in addition to the sample data that you posted:

    insert into orders_tb (order_id, order_date) values ('1001 ', to_date('13-JAN-2014','DD-MON-YYYY'));

    insert into orders_tb (order_id, order_date) values ('1001 ', to_date('19-JAN-2014','DD-MON-YYYY'));

    insert into orders_tb (order_id, order_date) values ('1001 ', to_date('25-JAN-2014','DD-MON-YYYY'));

    insert into orders_tb (order_id, order_date) values ('1003 ', to_date('01-JAN-2014','DD-MON-YYYY'));

    insert into orders_tb (order_id, order_date) values ('1003 ', to_date('10-JAN-2014','DD-MON-YYYY'));

    Here's one way:

    WITH got_next_date AS

    (

    SELECT DISTINCT

    order_id, order_date

    MIN (order_date) over (PARTITION BY order_id) AS start_date

    MIN (order_date) over (PARTITION BY order_id

    ORDER BY order_date

    RANGE BETWEEN 10.000001 MORE

    AND UNBOUNDED FOLLOWING

    ), Next_date

    Of orders_tb

    )

    SELECT order_id, order_date

    OF got_next_date

    START WITH order_date = start_date

    CONNECT BY order_date = next_date PRIOR

    AND order_id = order_id PRIOR

    ;

    Output (including the sample data, I added):

    ORDER_ID, ORDER_DATE

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

    1001 December 31, 2013

    1001 12 January 2014

    1001 January 25, 2014

    1002 February 2, 2014

    1002 2 March 2014

    1003 1 January 2014

  • Group records between trade unions

    Gurus,

    It's been a while since I formatted in SQL, but I have developed the following query, which gives me the result below:
         select distinct created_by, count(created_by) receipt_count,  null deliver_count
         from  wms_transaction
         where creation_date > sysdate-10
         and   transaction_type = 'RECEIPT'
         group by  created_by
       union
         select distinct created_by,  null rec_count,  count(created_by) deliver_count
         from  wms_transaction
         where creation_date > sysdate-10
         and   transaction_type = 'DELIVER'
         group by created_by   
         order by receipt_count
    
    CREATED_BY    RECEIPT_COUNT     DELIVER_COUNT
    --------------------   -----------------------     ------------------------
    SPRECKO                    4
    HKUMAR                     4
    SPRECKO                                            10
    HKUMAR                                           856
    The desired output is a user consolidated without additional records...
    CREATED_BY    RECEIPT_COUNT     DELIVER_COUNT
    --------------------   -----------------------     ------------------------
    SPRECKO                    4                       10
    HKUMAR                     4                     856
    Someone there all of the recommendations? I give the points to obtain useful and accurate responses (someone always comments on the points system when I write that ;-))

    Thank you
    Scott

    Published by: sreese on April 25, 2013 14:23

    Published by: sreese on April 25, 2013 14:23

    Hello

    You can do it with a pivot:

    select    created_by
    ,        count ( CASE
                      WHEN  transaction_type = 'RECEIPT'
                    THEN  created_by
                END
              )     as receipt_count
    ,        count ( CASE
                      WHEN  transaction_type = 'DELIVER'
                    THEN  created_by
                END
              )     as deliver_count
    from      wms_transaction
    where        creation_date    > sysdate - 10
    and          transaction_type IN ('DELIVER', 'RECEIPT')
    group by  created_by
    ;
    

    It will be much more effective than a UNION.

    The query above works in Oracle 8.1 or more. From Oracle 11, you can also use SELECT... PIVOT.

    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 {message identifier: = 9360002}

    Published by: Frank Kulash on 25 April 2013 14:37

  • Create table as select statement (ETG) takes a long time.

    Hi all

    One of my procedure launched a table create as select statement each month.
    Usually it ends in 20 minutes. for 6172063 records and 1 hour in 13699067.
    But this time it never even takes to 38076 records.
    When I checked everything he does is the CPU usage. No e/s.
    I did a count (*) using the query, it has brought very good results.
    BUT guard going on DEC.
    I use Oracle 10.2.0.4.
    temp_ip of the main table has 38076
    table nhs_opcs_hier has 26769 records.
    and table nhs_icd10_hier 49551 records.
    -------------------
    Query is:
    create the table analytic_hes.temp_ip_hier as
    Select b.*, (select nvl (max (hierarchy), 0))
    of ref_hd.nhs_opcs_hier one
    where fiscal_year = b.hd_spell_fiscal_year
    and a.code in
    (primary_PROCEDURE, secondary_procedure_1, secondary_procedure_2,
    secondary_procedure_3, secondary_procedure_4, secondary_procedure_5,
    secondary_procedure_6, secondary_procedure_7, secondary_procedure_8,
    secondary_procedure_9, secondary_procedure_10,
    secondary_procedure_11, secondary_procedure_12)) as hd_procedure_hierarchy,
    (select nvl (max (hierarchy), 0) for ref_hd.nhs_icd10_hier one)
    where fiscal_year = b.hd_spell_fiscal_year
    and a.code in
    (primary_diagnosis, secondary_diagnosis_1,
    secondary_diagnosis_2, secondary_diagnosis_3,
    secondary_diagnosis_4, secondary_diagnosis_5,
    secondary_diagnosis_6, secondary_diagnosis_7,
    secondary_diagnosis_8, secondary_diagnosis_9,
    secondary_diagnosis_10, secondary_diagnosis_11,
    secondary_diagnosis_12, secondary_diagnosis_13,
    secondary_diagnosis_14)) as hd_diagnosis_hierarchy
    of analytic_hes.temp_ip b
    -----------------

    Any help would be greatly appreciated

    Hello

    It is a bit of a wild card, I think because it will require 14 scans to fill the table temp_ip to unpivot codes diagnostic and procedure, so this lilkely things are moving slower than the original. However, as it is a temporary table, I guess you could have some control over its structure, or at least be able to dismiss it and try something else. If you are able to change the structure of this table, you could make the application much simpler and probably much faster. I think that you need a list of codes of procedure for the year and a list of diagnosis for fiscal codes. I do this through the large list of UNION all THE INSTRUCTIONS, but you can have a more efficient way to do according to the base tables you are people temp_ip of. In any case, it's here (as far as I can tell this will do the same job)

    WITH codes AS
    (   SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            primary_PROCEDURE       procedure_code,
            primary_diagnosis       diagnosis_code,
        FROM
            temp_ip
        UNION ALL
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_1    procedure_code,
            secondary_diagnosis_1    diagnosis_code
        FROM
            temp_ip
        UNION ALL
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_2    procedure_code ,
            secondary_diagnosis_2    diagnosis_code
        FROM
            temp_ip
        UNION ALL
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_3    procedure_code,
            secondary_diagnosis_3    diagnosis_code
        FROM
            temp_ip
        UNION ALL
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_4    procedure_code,
            secondary_diagnosis_4    diagnosis_code
        FROM
            temp_ip
        UNION ALL
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_5    procedure_code,
            secondary_diagnosis_5    diagnosis_code
        FROM
            temp_ip
        UNION ALL
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_6    procedure_code,
            secondary_diagnosis_6    diagnosis_code
        FROM
            temp_ip
        UNION ALL
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_7    procedure_code,
            secondary_diagnosis_7    diagnosis_code
        FROM
            temp_ip
        UNION ALL
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_8    procedure_code,
            secondary_diagnosis_8    diagnosis_code
        FROM
            temp_ip
        UNION ALL
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_9    procedure_code,
            secondary_diagnosis_9    diagnosis_code
        FROM
            temp_ip
        UNION ALL
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_10  procedure_code,
            secondary_diagnosis_10    diagnosis_code
        FROM
            temp_ip
        UNION ALL
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_11  procedure_code,
            secondary_diagnosis_11    diagnosis_code
        FROM
            temp_ip
        SELECT
            bd.primary_key_column_s,
            hd_spell_fiscal_year,
            secondary_procedure_12  procedure_code,
            secondary_diagnosis_12    diagnosis_code
        FROM
            temp_ip
    ), hd_procedure_hierarchy AS
    (   SELECT
            NVL (MAX (a.hierarchy), 0) hd_procedure_hierarchy,
            a.fiscal_year
        FROM
            ref_hd.nhs_opcs_hier a,
            codes pc
        WHERE
            a.fiscal_year = pc.hd_spell_fiscal_year
        AND
            a.code = pc.procedure_code
        GROUP BY
            a.fiscal_year
    ),hd_diagnosis_hierarchy AS
    (   SELECT
            NVL (MAX (a.hierarchy), 0) hd_diagnosis_hierarchy,
            a.fiscal_year
        FROM
            ref_hd.nhs_icd10_hier a,
            codes pc
        WHERE
            a.fiscal_year = pc.hd_spell_fiscal_year
        AND
            a.code = pc.diagnosis_code
        GROUP BY
            a.fiscal_year
    )
    SELECT b.*, a.hd_procedure_hierarchy, c.hd_diagnosis_hierarchy
      FROM analytic_hes.temp_ip b,
           LEFT OUTER JOIN hd_procedure_hierarchy a
              ON (a.fiscal_year = b.hd_spell_fiscal_year)
           LEFT OUTER JOIN hd_diagnosis_hierarchy c
              ON (c.fiscal_year = b.hd_spell_fiscal_year)
    

    HTH

    David

  • Return multiple values from a function in a SELECT statement

    I hope I've provided enough information here. If not, let me know what I'm missing.

    I create a view that will combine the information from several tables. Most are pretty simple, but there are a couple of columns in the view that I need to get by running a function within a package. Even if this is quite simple (I have a function named action_date in a package called rp, for example, that I can use to return the date that I need through SOME rp.action_date (sequence_number).

    Here is the question: I really need to return several bits of information of the same record (not only action_date, but also action_office, action_value, etc.)-a join of the tables will work not here, as I will explain below. I can, of course, perform a function separate for each statement, but this is obviously inefficient. Within the select statement of the view, however, I don't know how each of the values that I need to get back.

    For example, right now, I have:

    Table 1:
    sequence_number NUMBER (10),
    name varchar (30),
    ...

    Table2:
    Table1_seq NUMBER (10),
    action_seq NUMBER (10),
    action_date DATE,
    action_office VARCHAR (3),
    action_value VARCHAR (60),
    ...

    I can't just simply join Table1 and Table2 because I have to perform processing in order to determine the rows returned matching, I really need to select. If the package opens a cursor and treats each line until it finds the one I need.

    The following works but is ineffective since all calls to the package returns the columns of the same record. I don't know how to put all the values that I need in the SELECT statement.
    CREATE VIEW all_this_stuff AS
    SELECT sequence_number, name,
    RP.action_date (sequence_number) action_date,
    RP.action_office (sequence_number) action_office,
    RP.action_value (sequence_number) action_value
    FROM table1

    Is there a way to return multiple values in my SELECT statement or I'm going about this all wrong?

    Any suggestions?

    Thank you very much!

    Hello

    What you want is a Query of Top - N , what you can do using the ROW_NUMBER analytic function in a subquery, like this:

    WITH     got_rnum     AS
    (
         SELECT     action_seq, action_dt, action_office, action_type, action_value
         ,     ROW_NUMBER () OVER ( ORDER BY  action_date
                                   ,            action_seq
                             ,            action_serial
                           ) AS rnum
         FROM     table2
         WHERE     action_code     = 'AB'
         AND     action_office     LIKE 'E'     -- Is this right?
    )
    SELECT     action_seq, action_dt, action_office, action_type, action_value
    FROM     got_rnum
    WHERE     rnum     = 1
    ;
    

    As written, this returns a single line (at most).
    I suspect you'll actually get a rank for each group , where a group is defined by a value in a table in which you join.
    In this case, add a PARTITION BY clause to the ROW_NUMBER function.
    If post you a small example of data (CREATE TABLE and INSERT statements), I could show you exactly how.
    As I don't have your tables, I'll show you the use of the tables in the scott schema.
    This is a view containing data in the scott.dept table and also to scott.emp, but only for the highest employee in each Department (in other words, the employee whose oldest hire date). If there be a tie for the first hire date, while the candidate with the lowest empno is selected.

    CREATE OR REPLACE VIEW     senior_emp
    AS
    WITH     got_rnum     AS
    (
         SELECT     d.deptno
         ,     d.dname
         ,     e.empno
         ,     e.ename
         ,     e.hiredate
         ,     ROW_NUMBER () OVER ( PARTITION BY  d.deptno
                                   ORDER BY          e.hiredate
                             ,                e.empno
                           ) AS rnum
         FROM     scott.dept     d
         JOIN     scott.emp     e     ON     d.deptno     = e.deptno
    )
    SELECT     deptno
    ,     dname
    ,     empno
    ,     ename
    ,     hiredate
    FROM     got_rnum
    WHERE     rnum     = 1
    ;
    
    SELECT     *
    FROM     senior_emp
    ;
    

    Output:

    .    DEPTNO DNAME               EMPNO ENAME      HIREDATE
    ---------- -------------- ---------- ---------- ---------
            10 ACCOUNTING           7782 CLARK      09-JUN-81
            20 RESEARCH             7369 SMITH      17-DEC-80
            30 SALES                7499 ALLEN      20-FEB-81
    

    Moreover, one of the conditions to the query you posted has been

    action_office     LIKE 'E'
    

    which equals

    action_office     = 'E'
    

    (AS is always equivalent to = if the string that follows AS does not contain the winning cards.)
    Did you mean say that or did you mean something like this:

    action_office     LIKE 'E%'
    

    Instead?

  • normalize the schema of the table in a select statement (without view)

    Hello

    I have a table storing a physical value, mean temperature for different locations every minute. The table schema is as following: timestamp (datetime), rental (string), value (number).

    Do you know a way to have a select statement, return of lines with the following data: timestamp, the value at location1, value of place.2 guests, etc.

    This will help me to create time series in he same diagram in my reporting tool.

    This may be possible with a view, but I don't have access to the database, the best I can do is set my a data source such as a select statement.

    Thank you!

    Brahim

    PS. We use Oracle 10 g R2

    Hello

    8e07ad81-CDAE-4c23-b0fb-b6cd117cf5bc wrote:

    Hello

    I have a table storing a physical value, mean temperature for different locations every minute. The table schema is as following: timestamp (datetime), rental (string), value (number).

    Do you know a way to have a select statement, return of lines with the following data: timestamp, the value at location1, value of place.2 guests, etc.

    This will help me to create time series in he same diagram in my reporting tool.

    This may be possible with a view, but I don't have access to the database, the best I can do is set my a data source such as a select statement.

    Thank you!

    Brahim

    PS. We use Oracle 10 g R2

    What you're asking about is called pivoting.  The ahs Forum FAQ page devoted to this topic: Re: 4. How can I convert rows to columns?

    Since you're using Oracle 10, you cannot use the SELECT... Function PIVOT; You can use GROUP BY and CASE instead.

    Do ' t worry not about creating views.  What you can do with views, you can also do it using a WITH clause in your query.

    If you get stuck, please post some sample data (CREATE TABLE and only relevant columns, INSERT statements) for all of the tables involved and also to publish the results you want from this data, as well as your best attempt to query a specific question.

    Explain, using specific examples, how you get the results desired from data provided.

    See the FAQ forum: Re: 2. How can I ask a question on the forums?

  • function() nested in the select statement

    Oracle 11g. Try to nest a function within the select statement.  Goal: get the average customer rating for each of the qualified user.

    Select user_name, f_get_avg_cust_rating() "Notation.

    of u, OTHER_TABLES o TAB_USER

    where u.id = o.id and another condition matched;

    How Oracle would deal with the sql.  Is it

    (1) first of all display records based on the where clause, then call the f_get_avg_cust_rating() for each of the selected records OR

    (2) for the analysis in tables, the f_get_avg_cust_rating() will be called for each record met?

    Thank you

    Scott

    Words of Frank, I created two functions with dbms_output and used a function in where clause in select another function. See the bottom of the unit tests. Everyone says, where first clause then select...

    -Where function clause

    SQL > CREATE or REPLACE FUNCTION ret_empno

    2 RETURN NUMBER

    3 AS

    4 BEGIN

    5 DBMS_OUTPUT. Put_line (' where Clause Function');

    6 RETURN 7839;

    7 END;

    8.

    The function is created.

    -Select the function

    SQL > CREATE or REPLACE FUNCTION ret_1

    2 RETURN NUMBER

    3 AS

    4 BEGIN

    5 DBMS_OUTPUT. Put_line ('Select function');

    6 RETURN 1;

    7 END;

    8.

    The function is created.

    SQL > SELECT empno, ename,ret_1

    2 FROM emp

    3. WHERE empno = ret_empno;

    EMPNO, ENAME RET_1

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

    7839 KING 1

    Where the function Clause

    Select the function

Maybe you are looking for