How to generate the SQL statement

Hello

Here is the table and the data, and I did the solution using a pl/sql cursor.
This is possible in a SQL statemnt?




create the table TEMP_DISTINCT
(
NUMBER of allocation A_ID not null,
B_ID NUMBER not null,
C_VAL VARCHAR2 (30)
)


INSERT INTO TEMP_DISTINCT(A_ID,B_ID,C_VAL) VALUES(111,2222,'One')
INSERT INTO TEMP_DISTINCT(A_ID,B_ID,C_VAL) VALUES(111,2222,'Two')
INSERT INTO TEMP_DISTINCT(A_ID,B_ID,C_VAL) VALUES(112,2222,'Three')
INSERT INTO TEMP_DISTINCT(A_ID,B_ID,C_VAL) VALUES(112,2222,'Four')
INSERT INTO TEMP_DISTINCT(A_ID,B_ID,C_VAL) VALUES(112,2221,'Five')
INSERT INTO TEMP_DISTINCT(A_ID,B_ID,C_VAL) VALUES(112,2221,'Six')


declare
vorgid varchar2 (30);
CUR cursor is
Select distinct A_ID, B_ID from TEMP_DISTINCT
order by A_ID, B_ID;
Start
for the curs in news
loop
Select C_VAL
in TEMP_DISTINCT vorgid
where curs. A_ID = A_ID
and curs. B_ID = B_ID
and rownum = 1;

dbms_output.put_line (curs. A_ID | ' : ' || curs. B_ID | ':' || substr (vorgid, 1, 22));
end loop;
end;

Output
-------------
111: 2222:One
112: 2221:Five
112: 2222:Three

Hello

When you use ROWNUM directly on a table or a set of view or a result that is not an ORDER BY clause, results are for an indefinite period, in other words, there is no guarantee that you will get the same results every time that you run the query, even if the table has not changed.

The ROW_NUMBER analytic function can be used instead of ROWNUM. ROW_NUMBER can be calculated several different sequences (on different partitions of the result set) at the same time, like this:

WITH    got_rnum    AS
(
    SELECT  a_id
    ,       b_id
    ,       c_val
    ,       ROW_NUMBER () OVER  (PARTITION BY  a_id, b_id
                                 ORDER BY      ROWID
                                )   AS rnum
    FROM    temp_distinct
)
SELECT  a_id
,       b_id
,       c_val
FROM    got_rnum
WHERE   rnum    = 1
;

When you use ROW_NUMBER, you have to ORDER SOMETHING. In a very small table, like the sample, arbitrary results could come in the ROWID in your PL/SQL code order, so I used "ORDER OF ROWID" above. I could have used a constant, for example "ORDER OF 0.

Tags: Database

Similar Questions

  • How to execute the sql statement in the file beats?

    I want to execute after the statement
    C:\ > sqlplus/nolog
    SQL > conn scott/tiger
    SQL > select * from tab;

    I know I can achieve it following test.bat and testdb.sql file
    test.bat is:
    sqlplus/nolog @testdb.sql

    TestDB.SQL is:
    Conn scott/tiger
    Select * from tab;

    Now I don't want to use the sql file, I want only use bat file, as follows:
    test.bat is:
    sqlplus/nolog
    Conn scott/tiger
    Select * from tab;

    When I run test.bat, I find only one sqlplus /nolog execute statement, do not execute other statements.
    (1) I want to know if there is a method to run the SQL file by fighting without a sql file? How to make it happen?
    (2) if I call the sql file, how to hide the password of user? Because I don't want other people to know scott password, if I use conn scott/tiger in testdb.sql, other person can see testdb.sql and the password. Is there a good way to avoid?

    Thank you!

    It works a bit different in Windows. Create a file is like this:

    (
      echo conn scott/tiger@orcl
      echo spool c:\temp\list.txt
      echo select sysdate from dual;
      echo spool off
      echo exit
    ) | sqlplus -s -l /nolog
    
  • How to execute the SQL statement in the Application Module

    Hi people
    I´d would like to know how I can execute a SQL statement like "remove user" in the Module to request... prepareSession method...
    I m using Jdev 10 with ADF Faces
    Thank you

    This is possible, but you should think twice about it.
    If this can be done with an EO/VO do in this way.
    If you can't do it with an EO/VO you can yourself the DB operation (ApplicationModule.getDBTransaction ()) and use a call of createStatement (...) do what you want.

    Timo

  • How to remove the sql statement in the output of the coil?

    Hi gurus,

    If my spool request is like that
    set feedback off
    set verify off
    set trimspool on
    set heading off
    
    spool c:\test\test.csv
     select * FROM test;
     spool off
    I get my file csv as like this:
    SELECT * FROM test1
    
    SSO                  
    -------------------- 
    shsrgh               
    dehrerdh             
    wtw55hd              
    dhdfhdfh             
    hdhdh                
    
    
    SET SPOOL OFF;
    What should I change in my SQL query such that I won't include these lines:
    SELECT * FROM test1
    
    SSO                  
    -------------------- 
    
    SET SPOOL OFF;
    Thank you

    user10679113 wrote:

    What should I change in my SQL query such that I won't include these lines:

    SELECT * FROM test1
    
    SSO
    -------------------- 
    
    SET SPOOL OFF;
    

    You cannot change anything in your SQL query to exclude these lines.
    These lines refer to the client you are using i.e. SQL * more and have nothing to do with the SQL language as such.

    You could put all of these SQL * more commands in a script file and run this SQL script file *, as shown below:

    test@ORA10G>
    test@ORA10G> -- show contents of the script: c:\test.sql
    test@ORA10G> host type c:\test.sql
    set feedback off
    set trimspool on
    set heading off
    set echo off
    spool c:\test.log
    select ename from emp;
    spool off
    set echo on
    set heading on
    set feedback on
    
    test@ORA10G>
    test@ORA10G> -- run the script
    test@ORA10G> @c:\test.sql
    
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    KING
    TURNER
    ADAMS
    JAMES
    FORD
    MILLER
    test@ORA10G> set heading on
    test@ORA10G> set feedback on
    test@ORA10G>
    test@ORA10G> -- show contents of the spooled file: c:\test.log
    test@ORA10G> host type c:\test.log
    
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    KING
    TURNER
    ADAMS
    JAMES
    FORD
    MILLER
    
    test@ORA10G>
    

    HTH,
    isotope

  • How to rewrite the sql statement?

    Hello my query goes like this:

    Select a, b, c
    from (select 5A, b null, null double c
    Union of all the
    Select null, 4, the double null
    Union of all the
    Select 10, 3, double null) test_tab;

    and I want to get the result

    5 null null
    null null 4
    10 null null
    3 null null

    How can I rewrite the query without changing the structure of a table?

    Kind regards
    Igor

    Hello

    A way

    select a, null b, null c from test_tab where a is not null
    union all
    select null, b, null from test_tab where b is not null
    union all
    select null, null, c from test_tab where c is not null
    

    Concerning
    Anurag

  • How to generate the CSV file by coil

    Hello
    While running the script file Unix spool, it will show the output in Unix.
    And the file is created with query results from nd.
    I don't want the result expected in CSV file.

    set pagesize 10000
    the value of colsep «»
    Set feedback off
    set the position
    trigger the echo
    coil /home/tata/time.csv
    Select * from emp;
    spool off
    set echo on
    topic on the value
    Set of feedback on

    Thank you
    Lony

    lony wrote:
    I tried the sub query but still, it shows the output
    How to stop the putput.

    set pagesize 10000
    the value of colsep «»
    termout off Set
    Set feedback off
    set the position
    trigger the echo

    coil /home/tata/time.csv

    spool off
    Set termout on
    set echo on
    topic on the value
    Set of feedback on

    Place these commands alongwith your query into a file and then run it from the SQLPlus command line.
    There is no way the query statement delete appear in file queued if stuck directly into the SQLplus command prompt.
    How to remove the sql statement in the output of the coil?

  • Tuning sql of a product to the seller without changing the sql statement

    Hello

    We have a product of the provider that generates the SQL statement. For a query, we get the answer in 15 seconds. But users are asking if we can bring it back to 5 seconds. Limitation is the query can not be changed. He used about 10 to 12 tables and bit complex query.

    What kind of options could be evaluated if we are to improve the performance of a query (not sure if she could never be reduced to 5 seconds)
    without making any change to the query.

    Database Version: Oracle 10.2.0.4

    Thank you
    Delphine

    Hello

    http://www.Oracle-base.com/articles/10G/AutomaticSQLTuning10g.php

    your software is enterprise or standard?

    Tuning Pack & pack diagnosis are extra cost option with the standard edition.

    & the useful note * automatic SQL Tuning - SQL [271196.1 ID] profiles *.

    http://www.Oracle.com/us/corporate/pricing/technology-price-list-070617.PDF

    Thank you

    Published by: CKPT November 5, 2010 11:12

  • How to write the Sql values in the Application Engine

    I am trying to write dynamic sql statements in AE
    E.g.
    I have SQL n Action
    DELETE
    OF %Table(%BIND(RECNAME))
    WHERE Bind (FIELDNAME) = % (AMIT_VALUE_TO_DEL) Bind %;

    at runtime, it converts into

    DELETE
    OF PS_TABLE1
    WHERE 'EMPLID '=' AJ23;

    THE QUOTATION MARK SINGLE AROUND EMPLID IN WHERE CLAUSE CREATES PROBLEM BCZ, IT IS A COLUMN NAME, IS THERE A SOLUTION THIS?

    Add NOQUOTES to your % Bind(). For example, % (FIELDNAME, NOQUOTES) Bind.

    I must warn you however. When generating dynamic SQL, make sure that you have absolute control over the input text used to generate the SQL statement. For example, make sure that you, not a user, determines the value of RECNAME and FIELDNAME. It is too easy to create a SQL Injection flaw in converting the values entered by the user in SQL statements.

  • How to get the SQL if I get exception

    I get this exception and do not know what was the actual sql with the variables of liaison who was executed.



    sqlmesg = error in the select query to retrieve the segment associated with a pair of cables: ORA-01006: there is no bind variable

    y at - it a way to get the real sql executed so I know what mistake I did.

    I thought your question was about how to view the SQL statement and bind variables in the exception. The answer to that is to put variables in the exception message.

    The root cause of the problem seems to be that your dynamic SQL statement may require 3 or4 variable bind but your USING clause specifies always 4 values if the underlying SQL statement has 3 positions, it will lead to an error.

    Justin

  • How to analysis of the XML in the sql statement?

    Hi friends, I have a table that contains a column of type CLOB, stores in xml format. For example, the data are like that

    <Employees xmlns="http://TargetNamespace.com/read_emp">
       <C1>106</C1>
       <C2>Harish</C2>
       <C3>1998-05-12</C3>
       <C4>HR</C4>
       <C5>1600</C5>
       <C6>10</C6>
    </Employees>
    
    

    So how can I write the sql statement for the analysis of the data at the top

    create or replace procedure parsing_xml

    (

    clob trans_payload

    trans_dir varchar2

    )

    as

    Start

    if(trans_dir='inbound/emp')

    then

    insert into emp_proj

    (

    employee_id

    last_name

    hire_date

    job_id

    salary

    department_id

    )

    Select t1.c1

    t1.c2

    t1.c3

    t1.c4

    t1.c5

    t1.c6

    from xmltable

    (

    XmlNamespaces ('http://TargetNamespace.com/read_emp' as 'emp').

    ' / ' emp:Employees by the way of xmltype (trans_payload)

    columns

    whole path of C1 'emp:C1. "

    path of varchar2 (10) C2 'emp:C2. "

    C3 varchar2 (10) path "emp:C3."

    C4 varchar2 (10) path "emp:C4."

    whole path of C5 "emp:C5."

    C6 varchar2 (10) path 'emp:C6 '.

    ) t1;

    end if;

    commit;

    end;

  • How the SQL statement

    In an interview, no one asked me a question. How the sql statement
    ex: select * from emp;

    I answered him as if the select statement is in the library cache then it will retrieve data from the cache, otherwise it will retrieve data from database files. On this, he asked to go. I could not years itself. Anyone like elobarate me on the analysis?

    SMON,

    I would have preferred the official documents from Oracle, as suggested by

    http://download.Oracle.com/docs/CD/E11882_01/server.112/e16508/sqllangu.htm#CHDFCAGA

    Concerning
    Peter

  • How to see the sql on the tables verified statements?

    Hi all

    I just check schema as the following comment run

    AUDIT UPDATE TABLE DELETE TABLE INSERT TABLE BY user1, user2 BY ACCESS;

    However, I could not find the SQL statements.

    SELECT A.TIMESTAMP, A.* DE DBA_AUDIT_TRAIL A

    Username = ' USER1'

    Also, this does not work, it shows empty

    select sql_text from sys. aud$ obj$ nom = « TAB_PROJELOG »


    Oracle Database 11 g Release 11.2.0.4.0 - 64 bit Production

    • db

      Redirect audit records to the database audit trail (the SYS.AUD$ table), except for records that are always written in the track operating system audit. Use this setting for a general database for administration.

      If the database is started in read-only mode with AUDIT_TRAIL defined on db , then affects the Oracle database internally AUDIT_TRAIL to os . Check the log of alerts for details.

    • db, extended

      Performs all the actions of AUDIT_TRAIL = db and fulfills also the bind SQL and SQL CLOB type text columns of the SYS.AUD$ table, when it is available. These two columns are filled only when specified.

      If the database is started in read-only mode with AUDIT_TRAIL defined on db, extended , then affects the Oracle database internally AUDIT_TRAIL to os . Check the log of alerts for details.

    https://docs.Oracle.com/CD/E11882_01/server.112/e40402/initparams017.htm#REFRN10006

  • How can I pass a condition of the table in the sql statement?

    For example, in the table in the COND Varchar2 column (200) there is the value ' VAR > 10'.

    | COND |

    |' VAR > 10' |

    where VAR is the name of the table column. I would like to make statement CASE WHEN VAR > 10 AND 0... I tried with as subquery

    WHEN BOX (SELECT COND FROM TABLE WHERE...) THEN 0, but it does not work.

    Hello

    You can do this by using dynamic SQL.

    that is to say:

    declare
      v_stm      varchar2(4000);
      v_cond      varchar2(100);
      v_result    integer;
    begin
      select cond
        into v_cond
        from yourtable
      where a=1;
    
      v_stm := 'select case when '||v_cond||' then 0 ...';
    
      -- dynamic sql
      execute immediate v_stm
        into v_result;
    
    end;
    /
    

    Remember that, in general, dynamic SQL has a performance degradation that SQL static and should be avoided when possible.

    Storage condition or the SQL statements in the tables is not a good practice.

    Kind regards.

    Alberto

  • Get the SQL statement error programmatically

    Hello

    error SQL in the FORMS, you can display the erroneous SQL statement pressing (shift) (Ctrl) E on the screen. Is there a way to get the text of the SQL statement in a PL/SQL function for logging purposes?

    I get the error using SQLERRM, it's not a problem. But how can I get the SQL text of the statement?

    Thanks and regards,

    Sascha

    Sascha,

    You should be able to use the: SYSTEM. System LAST_QUERY variable forms.

    Craig...

  • How to run a SQL statement to use a specific implementation plan

    Hi all

    I have a SQL that has recently been run badly. I tried the Advisor tuning SQL for the given SQL query and it gives the following information:

    GENERAL INFORMATION SECTION

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

    Name of the task of tuning: 2q94zb7djr2xn

    The owner task of tuning: LMDBPROD

    Type of work: single SQL statement

    County of execution: 2

    The current run: EXEC_8869

    Type of execution: TUNE SQL

    Scope: COMPLETE

    Time Limit (seconds): 60

    Status: COMPLETED

    Started on the: 03/02/2014-20:43:39

    To the: 03/02/2014 20:44:25

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

    Name of the schema: LMDBPROD

    SQL ID: 2q94zb7djr2xn

    SQL text: SELECT NPCOMMON. FGET_ACTION_CODE (ORDNUM) ACTIONCODE, STATUS,

    SUMA COUNT (*) FROM SORDER, WHERE HEADORDNUM IS NOT NULL AND

    NPCOMMON. FGET_PRODUCTOFFER4ORDER (ORDNUM) IN (SELECT ID FROM)

    PRODUCTOFFER WHERE PPSPECIFICATION_ID IN (SELECT ID FROM)

    PPSPECIFICATION WHERE PCLASS_CODE IN (SELECT PCLASS_CODE FROM)

    ARUSERGROUP WHERE CODE IN (SELECT ARUSERGROUP_CODE FROM)

    ARUSER_ARUSERGROUP WHERE ARUSER_USERNAME =: B1 AND STATUS = '1')

    AND STATUS = '1'))) GROUP BY NPCOMMON. FGET_ACTION_CODE (ORDNUM),

    STATUS

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

    RESULTS SECTION (1 result)

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

    1-alternative Plan conclusion

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

    Some implementation plans alternative for this statement was found by searching

    performance data in real-time and historical of the system.

    The following table lists these plans sorted by their average time.

    See "SECTION of ALTERNATIVE PLANS" section for detailed information on each

    plan.

    plan ID hash last visit elapsed note of origin (s)

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

    1 617797893 2013-07-11/07: 45:20 9.555 no reproducible STS

    2 1311086720 2014-01-31/04: 00:44 19.569 AWR

    3 1226863820 2014-01-31/18: 00:24 AWR 21.158

    4 1359606848 2014-02-03/16: 00:34 21.492 AWR original plan

    The plan with hash 617797893 seems the most efficient one and is based on some specific SQL Tuning Set I ran on this time. But the note says that the plan is not reproducible. Is there anyway how can I force the SQL statement to execute the plan? The database version is Standard Edition 11.2.0.1.0

    Best regards

    Rodriguez

    Hello

    I think you can use this

    http://rnm1978.WordPress.com/2011/06/28/Oracle-11g-how-to-force-a-sql_id-to-use-a-plan_hash_value-using-SQL-baselines/

    before 11 g, we used to create an outline stored for this.

    concerning

Maybe you are looking for

  • Lonely Spider has no animation

    The animation in the options box is gray, how to activate it?

  • get the 8024000 error code when trying to install sp2 to vista tried about 6 times

    Windows says I have 1 important update, when I try to install the update I get an error code 8024000 I installed sp1 without problem, but have tried about 6 times with sp2 and nowhere

  • My sim card adapter does not work on my laptop.

    I have a sim micro sd card for my phone and an adapter for the laptop. When I plug in the adapter with the card, nothing happens, I can't find anywhere on my computer to open the files. Help, please!

  • Screen frozen blackBerry Smartphones

    Have had my PRIV for a day.  Download an attachment (or at least I thought I was downloading an attachment) when the screen is frozen.  Cannot switch the handset off to restart.  Any ideas?  I can't believe XXX hours for the battery to discharge of w

  • How can I make a pencil they turn?

    I create a horror movie with my friends in a few weekends and I'm trying to figure out special effects. In the movie a color pencil is supposed to return so that it points in the opposite direction, but to return until the point of first. In total, t