Distinct unique on select

Hello to all
I have this my sample
A.K_FRASE,TITOLO,A.K_FRASE,A.K_SPECIAL, A.K_PRESTA ,SORT_X_SHOW
E001     01-Fegato     E001     R1     3     1
E001     01-Fegato     E001     R1     1     1
E001     01-Fegato     E001     R1     17     1
E001     01-Fegato     E001     R1     2     1
E003     03-Steatosi     E003     R1     1     3
E003     03-Steatosi     E003     R1     2     3
E003     03-Steatosi     E003     R1     16     3
CREATE OR REPLACE VIEW V_FRASIREFERTO as
SELECT unique A.K_FRASE,TITOLO,A.K_FRASE,A.K_SPECIAL, A.K_PRESTA ,SORT_X_SHOW
FROM A_FRASI_REFERTO_PRESTA A, A_FRASI_REFERTO  B, A_PRESTA P
WHERE  A.K_FRASE = B.K_FRASE
AND A.K_PRESTA = P.K_PRESTA
AND A.K_SPECIAL = P.K_SPECIAL
AND A.TIPORD = P.TIPORD
and  A.K_FRASE in ( 'E001'  ,'E003')
ORDER BY 3,4,6;How can i get unique row (only one) that have same k_frase (E001,E003), that is
E001     01-Fegato     E001     R1     17     1
E003     03-Steatosi     E003     R1     1     3
Thanks in advance

Rosario,
Frank is suggesting you to do it this way:
CREATE OR REPLACE VIEW V_FRASIREFERTO as
SELECT K_FRASE,TITOLO,K_FRASE,K_SPECIAL, K_PRESTA ,SORT_X_SHOW
FROM (
SELECT A.K_FRASE,TITOLO,A.K_SPECIAL, A.K_PRESTA ,SORT_X_SHOW,
      row_number() over(partition by A.K_FRASE order by A.K_FRASE,A.K_SPECIAL, SORT_X_SHOW) rn
FROM A_FRASI_REFERTO_PRESTA A, A_FRASI_REFERTO  B, A_PRESTA P
WHERE  A.K_FRASE = B.K_FRASE
AND A.K_PRESTA = P.K_PRESTA
AND A.K_SPECIAL = P.K_SPECIAL
AND A.TIPORD = P.TIPORD
and  A.K_FRASE in ( 'E001'  ,'E003')
where rn=1
ORDER BY 3,4,6;Max
[My Italian Oracle blog|http://oracleitalia.wordpress.com/2010/01/23/la-forza-del-foglio-di-calcolo-in-una-query-la-clausola-model/]
Edited by: Massimo Ruocchio on Jan 29, 2010 1:37 PM
Correctly managed alias

Similar Messages

  • HT1766 How do i combine 2 distinctly unique backups so as to merge my notes and contacts ?  Can i simply restore both and the data will be merged, or will one complete backup merely overwrite the other ?

    How do i combine 2 distinctly unique backups so as to merge my notes and contacts ?  Can i simply restore both and the data will be merged, or will one complete backup merely overwrite the other ?

    you can't merge backups.  it's all or nothing.  one or the other.

  • Distinct dataset for selection combo box

    Hi,
    I have a dataset displayed on my page with paging and
    dependant detail region as well as filter functions. Works like a
    charm. For a visual look
    here
    My issue is this: To enable the filter with drop down select
    list (aka combo box) shown in the picture I implemented the
    following code
    var transactlist_xml = new
    Spry.Data.XMLDataSet("transactlist-xml.php",
    "export/row",{sortOnLoad:"account",sortOrderOnLoad:"ascending",useCache:false,loadInterva l:60000});
    var accounts_xml = new
    Spry.Data.XMLDataSet("transactlist-xml.php",
    "export/row/account",{sortOnLoad:"account",sortOrderOnLoad:"ascending",distinctOnLoad:tru e});
    The first dataset selects the data for the entire list, the
    second for the combo box. It works alright, but I deam it to be
    very inefficient. I have to call the php script that does the data
    selection twice, which means double the database load. Not good.
    Since I have selected all the data I need in the first statement,
    is away I can reduce the number of direct source reads and costruct
    the second dataset out of the first?
    I tried
    var accounts_xml = transactlist_xml.distinct();
    with no success, as transactist_xml has all the fields still
    included, so clearly the rows will not be distinct.
    Any suggestions/thougts?
    Any hint is appreciated.
    Hanno Schupp

    "How to Use The Focus Subsystem"
    http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html

  • Possible to not use DISTINCT keyword in select query?

    I have a high repetition query that polls the database and only ever uses
    the first row returned from the query. Using the distinct keyword adds
    overhead and increases the use of tempdb in SQL Server in order to remove
    any duplicates. Is there a way to instruct kodo not to use distinct on an
    ad-hoc basis?
    We are using 3.2.3 on SQL Server 2000
    Regards
    Nathan

    Unfortunately, no.

  • SELECT DISTINCT With OPEN cursor FOR

    Hello.
    I have the following procedure. All it does is open a cursor for an SQL string passed into it, and return the open cursor.
    PROCEDURE sp_execute_dynamic (hold_input_string IN CLOB,
    hold_cursor OUT hold_cursor_type) IS
    BEGIN
    OPEN hold_cursor FOR TO_CHAR(hold_input_string);
    END sp_execute_dynamic;
    It works fine except when I perform SELECT DISTINCT. I get the following error.
    SQL> declare
    2 TYPE hold_cursor_type IS REF CURSOR;
    3 hold_cursor hold_cursor_type;
    4 hold_object_name VARCHAR2(1024);
    5 hold_object_type VARCHAR2(1024);
    6 begin
    7 dynamic_sql_pkg.sp_execute_dynamic('select distinct object_name from user_objects where object_
    name in (''PLAN_TABLE'',''DBA_OBJECTS'')',hold_cursor);
    8 loop
    9 fetch hold_cursor into hold_object_name, hold_object_type;
    10 exit when hold_cursor%NOTFOUND;
    11 dbms_output.put_line('Object Name = '||hold_object_name||' Object Type = '||hold_object_type);
    12 end loop;
    13 end;
    14 /
    declare
    ERROR at line 1:
    ORA-01007: variable not in select list
    ORA-06512: at line 9
    It does the same thing with SELECT UNIQUE or SELECT with a GROUP BY. Can anyone tell me why this happens and what I could to to work around it?
    Thanks
    Chris

    see at line 7 you are selecting only one column and at line 9you are fetching into two variables
    7 dynamic_sql_pkg.sp_execute_dynamic('select distinct object_name from user_objects where object_
    name in (''PLAN_TABLE'',''DBA_OBJECTS'')',hold_cursor);
    8 loop
    9 fetch hold_cursor into hold_object_name, hold_object_type;
    HTH

  • "connect by" problem with "select distinct"

    When I run the following SQL (using "Scott" DB):
    select *
    from emp
    where deptno = 30 or mgr is null
    start with mgr is null
    connect by prior empno = mgr
    order siblings by ename
    I get the results one would expect. The President is first and all those reporting to him/her are listed in correct sequence.
    EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO
    7839,KING,PRESIDENT,,11/17/1981,5000,10
    7698,BLAKE,MANAGER,7839,5/1/1981,2850,30
    7499,ALLEN,SALESMAN,7698,2/20/1981,1600,300,30
    7900,JAMES,CLERK,7698,12/3/1981,950,30
    7654,MARTIN,SALESMAN,7698,9/28/1981,1250,1400,30
    7844,TURNER,SALESMAN,7698,9/8/1981,1500,0,30
    7521,WARD,SALESMAN,7698,2/22/1981,1250,500,30
    However, when I run the same query but make it "select distinct" I get the following:
    EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO
    7499,ALLEN,SALESMAN,7698,2/20/1981,1600,300,30
    7698,BLAKE,MANAGER,7839,5/1/1981,2850,,30
    7900,JAMES,CLERK,7698,12/3/1981,950,,30
    7839,KING,PRESIDENT,,11/17/1981,5000,,10
    7654,MARTIN,SALESMAN,7698,9/28/1981,1250,1400,30
    7844,TURNER,SALESMAN,7698,9/8/1981,1500,0,30
    7521,WARD,SALESMAN,7698,2/22/1981,1250,500,30
    Why would adding "distinct" to the select cause the result to be sorted STRICTLY by ename (per "order siblings by...")?
    Finally, if I "select distinct" but don't specify any "order" I get this, in NO APPARENT order:
    EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO
    7499,ALLEN,SALESMAN,7698,2/20/1981,1600,300,30
    7521,WARD,SALESMAN,7698,2/22/1981,1250,500,30
    7654,MARTIN,SALESMAN,7698,9/28/1981,1250,1400,30
    7698,BLAKE,MANAGER,7839,5/1/1981,2850,,30
    7839,KING,PRESIDENT,,11/17/1981,5000,,10
    7844,TURNER,SALESMAN,7698,9/8/1981,1500,0,30
    7900,JAMES,CLERK,7698,12/3/1981,950,,30
    Thanks in advance for any insight offered!
    -Gene

    you have to specify what is going to be the distict field.No you don't. DISTINCT keyword applies to the whole SELECT list. See your own link.
    In any case this does not appear to have anything to do with what you SELECT, rather that the SORT UNIQUE caused by the DISTINCT keyword appears to prevent the ORDER SIBLINGS BY clause from working correctly.
    Not really sure why you need DISTINCT in this example, no doubt this is being applied elsewhere. Given that you have duplicates in the rowset and that hierarchical query now supports views, perhaps it would be more efficient to apply DISTINCT keyword first, something like...
    SELECT e.*
    FROM (SELECT DISTINCT e.*
    FROM emp e
    WHERE e.deptno = 30
    OR e.mgr IS NULL) e
    START WITH e.mgr IS NULL
    CONNECT BY PRIOR e.empno = e.mgr
    ORDER SIBLINGS BY e.ename;
    Alternatively you could skip ORDER SIBLINGS BY clause and use SYS_CONNECT_BY_PATH function to get your order, something like...
    SELECT e.*
    FROM (SELECT DISTINCT e.*,
    SYS_CONNECT_BY_PATH () path
    FROM emp e
    WHERE e.depno = 30
    OR e.mgr IS NULL
    START WITH e.mgr IS NULL
    CONNECT BY PRIOR e.empno = e.mgr) e
    ORDER BY e.path
    Padders

  • Distinct Select on Varchar2 Column

    Hi,
    I have a unique problem - (no pun intended) - pls bare with me while I explain...
    I have the following table (tbl_party) :
    p_num VARCHAR2(30)
    p_name VARCHAR2(100)
    p_cert NUMBER
    i_cat NUMBER
    p_stat DATE
    Test 1.
    When I do a select count(distinct(p_num)) from tbl_party;
    Return 6298 rows
    Test 2.
    When I do a select distinct(p_num) from tbl_party;
    Return 6298 rows
    Test 3.
    When I do a select distinct(p_num), p_cert from tbl_party;
    Return 6300 rows???
    Can some1 pls enlighten me if there is a limitation on distinct/unique when using it on VARCHAR2??
    Thanks in advance.
    Jaco

    I think in third test you get 6300 not 6298 because there are two additional value for the same values in p_num column.
    See this:
    SQL> ed
    Wrote file afiedt.buf
      1  with t as
      2  (select 1 as col1, 'abc' from dual
      3  union all
      4  select 2, 'bcd' from dual
      5  union all
      6* select 1, 'bcd' from dual)
    SQL> ed
    Wrote file afiedt.buf
      1  with t as
      2  (select 1 as col1, 'abc' from dual
      3  union all
      4  select 2, 'bcd' from dual
      5  union all
      6  select 1, 'bcd' from dual)
      7* select distinct(col1) from t
    SQL> /
          COL1
             1
             2
    SQL> ed
    Wrote file afiedt.buf
      1  with t as
      2  (select 1 as col1, 'abc' from dual
      3  union all
      4  select 2, 'bcd' from dual
      5  union all
      6  select 1, 'bcd' from dual)
      7* select count(distinct(col1)) from t
    SQL> /
    COUNT(DISTINCT(COL1))
                        2
    SQL> ed
    Wrote file afiedt.buf
      1  with t as
      2  (select 1 as col1, 'abc' as col2 from dual
      3  union all
      4  select 2, 'bcd' from dual
      5  union all
      6  select 1, 'bcd' from dual)
      7* select distinct(col1), col2 from t
    SQL> /
          COL1 COL
             1 bcd
             1 abc
             2 bcdAs you can see there are two values in col2 for one value in col1. That's why you get 6300 not 6298 even if you use DISTINCT.
    Peter D.

  • Query performance using distinct

    Greetings! We're on Oracle 8.1.7, Solaris 2.8.
    I have a query that utilizes a different access path if I use the word distinct in the select from this view. Here is our query:
    SELECT
    DISTINCT SETID,
    VENDOR_ID,
    VENDOR_NAME_SHORT,
    AR_NUM,
    NAME1,
    ADDRESS1,
    ADDRESS2,
    CITY
    FROM
    PS_VENDOR_VW
    WHERE
    SETID LIKE 'MNSA' AND
    NAME1='FUN' ORDER BY NAME1, SETID, VENDOR_ID
    The view SQL is:
    SELECT /*+ FIRST_ROWS */ a.setid
    , a.vendor_name_short
    , a.name1
    , c.address1
    , c.address2
    , c.city
    , a.vendor_id
    FROM SYSADM.ps_vendor a
    SELECT /*+ INDEX_ASC(B PSAVENDOR_ADDR) */
    FROM SYSADM.ps_vendor_addr b
    WHERE b.effdt = (
    SELECT MAX(effdt)
    FROM SYSADM.ps_vendor_addr
    WHERE setid = b.setid
    AND vendor_id = b.vendor_id
    AND address_seq_num = b.address_seq_num
    AND effdt <= sysdate)) c
    WHERE a.setid = c.setid (+)
    AND a.vendor_id = c.vendor_id (+)
    AND a.prim_addr_seq_num=c.address_seq_num (+)
    This query does an index full scan on an index for ps_vendor_addr. It takes 2+ minutes to run. Now, if I remove the word distinct, it uses an index range scan and "view pushed predicate". It runs in 2 seconds.
    I've tried with and without the first_rows hint in the view. If I leave off the INDEX_ASC hint then it does a full table scan of table ps_vendor_addr. It refuses to do a range scan with the hint. Can anybody tell me how I can get the 'distinct' query tuned?
    2 minutes may not seem like a lot but when online users run the query many times a day, it is very frustrating.
    Thanks! I hope I provided enough info.

    Thomas:
    The different behaviours you are seeing are a result of the DISTINCT in the query. This causes a sort to be performed, and will influence the way that the CBO will execute the query. (You do know that you are using the Cost Based Optimizer because of the hints, and that you should analyze the tables and indexes?) You need to be able to re-write the view to avoid the need for the DISTINCT in the query.
    Without knowing the meaning of the fields, it is really hard to say anything meaningful, but my guess is that it is the correlated sub-query that is ultimately causing the need for the DISTINCT. Is the combination of set_id,vendor_id and address_seq_num truly unique, or is the address_seq_num just a sequence.
    For example in one of my databases, I have a table with INDV_ID, EFF_DT, EMPSTAT_SEQ. The empstat_seq field is just there to allow for more than one thing happening on the same day. The way we query this table is:
    SELECT *
    FROM empstat_t a
    WHERE indv_id = :emp_id and
          TO_CHAR(eff_dt,'yyyymmdd')||TO_CHAR(empstat_seq,'009') =
                  (SELECT MAX(TO_CHAR(eff_dt,'yyyymmdd')||TO_CHAR(empstat_seq,'009')
                   FROM empstat_t
                   WHERE a.indv_id = indv_id);Could something similar work in your case?
    If not, assuming your statistics are up to date, I would also look at creating the view without hints to see what the optimizer comes up with on its own. It may be better than you think.
    TTFN
    John

  • Reg different kinds of select stmts

    Hi All,
    Hope all are doing gud,
    cud any tell me different kinds of select stmts ????
    regards,
    abc xyz

    hi,
    SELECT
    Basic form
    SELECT result [target] FROM source [where] [GROUP BY fields] [ORDER BY order].
    Effect
    Retrieves an extract and/or a set of data from a database table or view (see Relational database ). SELECT belongs to the OPEN SQL command set.
    Each SELECT command consists of a series of clauses specifying different tasks:
    The SELECT result clause specifies
    whether the result of the selection is a table or a single record,
    which columns the result is meant to have and
    whether the result is allowed to include identical lines.
    The INTO target clause specifies the target area into which the selected data is to be read. If the target area is an internal table, the INTO clause specifies
    whether the selected data is to overwrite the contents of the internal table or
    whether the selected data is to be appended to the contents and
    whether the selected data is to be placed in the internal table all at once or in several packets.
    The INTO clause can also follow the FROM clause.
    You can omit the INTO clause. The system then makes the data available in the table work area (see TABLES ) dbtab . If the SELECT clause includes a "*", the command is processed like the identical SELECT * INTO dbtab FROM dbtab statement. If the SELECT clause contains a list a1 ... an , the command is executed like SELECT a1 ... an INTO CORRESPONDING FIELDS OF dbtab FROM dbtab .
    If the result of the selection is meant to be a table, the data is usually (for further information, see INTO -Klausel ) read line by line within a processing loop introduced by SELECT and concluded by ENDSELECT . For each line read, the processing passes through the loop once. If the result of the selection is meant to be a single record, the closing ENDSELECT is omitted.
    The FROM source clause the source (database table or view ) from which the data is to be selected. It also determines
    the type of client handling,
    the behavior for buffered tables and
    the maximum number of lines to be read.
    The WHERE where clause specifies the conditions which the result of the selection must satisfy. It thus determines the lines of the result table. Normally - i.e. unless a client field is specified in the WHERE clause - only data of the current client is selected. If you want to select across other clients, the FROM clause must include the addition ... CLIENT SPECIFIED .
    The GROUP-BY fields clause combines groups of lines together into single lines. A group is a set of lines which contain the same value for every database field in the GROUP BY clause.
    The ORDER-BY order clause stipulates how the lines of the result table are to be ordered.
    Each time the SELECT statement is executed, the system field SY-DBCNT contains the number of lines read so far. After ENDSELECT , SY-DBCNT contains the total number of lines read.
    The return code value is set as follows:
    SY-SUBRC = 0 At least one line was read.
    SY_SUBRC = 4 No lines were read.
    SY-SUBRC = 8 The search key was not fully qualified.
    (nur bei SELECT SINGLE ). The returned single record is any line of the solution set.
    Example
    Output the passenger list for the Lufthansa flight 0400 on 28.02.1995:
    TABLES SBOOK.
    SELECT * FROM SBOOK
      WHERE
        CARRID   = 'LH '      AND
        CONNID   = '0400'     AND
        FLDATE   = '19950228'
      ORDER BY PRIMARY KEY.
      WRITE: / SBOOK-BOOKID, SBOOK-CUSTOMID,   SBOOK-CUSTTYPE,
               SBOOK-SMOKER, SBOOK-LUGGWEIGHT, SBOOK-WUNIT,
               SBOOK-INVOICE.
    ENDSELECT.
    Performance
    In client/server environments, storing database tables in local buffers (see SAP buffering ) can save considerable amounts of time because the time required to make an access via the network is much more than that needed to access a locally buffered table.
    Notes
    A SELECT command on a table for which SAP buffering is defined in the ABAP/4 Dictionary is normally satisfied from the SAP buffer by bypassing the database. This does not apply with
    - <b>SELECT SINGLE FOR UPDATE
    - SELECT DISTINCT in the SELECT clause ,
    - BYPASSING BUFFER in the FROM clause ,
    - ORDER BY f1 ... fn in the ORDER-BY clause ,
    - aggregate functions in the SELECT clause ,
    - when using IS [NOT] NULL WHERE condition ,</b>
    or if the generic key part is not qualified in the WHERE-Bedingung for a generically buffered table.
    Authorization checks are not supported by the SELECT statement, so you must program these yourself.
    In dialog systems, the database system locking mechanism cannot always guarantee to synchronize the simultaneous access of several users to the same dataset. In many cases, it is therefore advisable to use the SAP locking mechanism .
    Changes to data in a database are only finalized after a database commit (see LUW ). Prior to this, any database update can be reversed by a database rollback (see Programming transactions ). At the lowest isolation level (see the section on the "uncommitted read" under Locking mechanism ), this can result in the dataset selected by the SELECT command not really being written to the database. While a program is selecting data, a second program can add, change or delete lines at the same time. Then, the changes made by the second program are reversed by rolling back the database system. The selection of the first program thus reflects only a very temporary state of the database. If such "phantom data" is not acceptable for a program, you must either use the SAP locking mechanism or at least set the isolation level of the database system to "committed read" (see Locking mechanism ).
    In a SELECT-ENDSELECT loop, the CONTINUE statement terminates the current loop pass prematurely and starts the next.
    If one of the statements in a SELECT ... ENDSELECT loop results in a database commit, the cursor belonging to the SELECT ... ENDSELECT loop is lost and the processing terminates with a runtime error. Since each screen change automatically generates a database commit, statements such as CALL SCREEN , CALL DIALOG , CALL TRANSACTION or MESSAGE are not allowed within a SELECT ... ENDSELECT loop.
    Related OPEN CURSOR , FETCH und CLOSE CURSOR
    SELECT clause
    Variants
    1. <b>SELECT [SINGLE [FOR UPDATE] | DISTINCT] *
    2. SELECT [SINGLE [FOR UPDATE] | DISTINCT] s1 ... sn
    3. SELECT [SINGLE [FOR UPDATE] | DISTINCT] (itab)</b> Effect
    The result of a SELECT statement is itself a table . The SELECT clause describes which columns this table is supposed to have.
    In addition, you can use the optional addition SINGLE or DISTINCT if you want only certain lines of the solution set to be visible for the calling program:
    SINGLE The result of the selection is a single record . If this record cannot be uniquely identified, the first line of the solution set is selected. The addition FOR UPDATE protects the selected record against parallel changes by other transactions until the next database commit occurs (see LUW and Database locking ). If the database system detects a deadlock, the result is a runtime error.
    DISTINCT Any lines which occur more than once are automatically removed from the selected dataset.
    Note
    To ensure that a record is uniquely determined, you can fully qualify all fields of the primary key by linking them together with AND in the WHERE condition.
    Note
    Performance
    The additions SINGLE FOR UPDATE and DISTINCT exclude the use of SAP buffering .
    The addition DISTINCT requires sorting on the database server and should therefore only be specified if duplicates are likely to occur.
    Variant 1
    SELECT [SINGLE [FOR UPDATE] | DISTINCT] *
    Effect
    In the result set, the columns correspond exactly in terms of order, ABAP/4 Dictionary type and length to the fields of the database table (or view ) specified in the FROM clause .
    Example
    Output all flight connections from Frankfurt to New York:
    TABLES SPFLI.
    SELECT * FROM SPFLI
             WHERE
               CITYFROM = 'FRANKFURT' AND
               CITYTO   = 'NEW YORK'.
      WRITE: / SPFLI-CARRID, SPFLI-CONNID.
    ENDSELECT.
    Example
    Output all free seats on the Lufthansa flight 0400 on 28.02.1995:
    TABLES SFLIGHT.
    DATA   SEATSFREE TYPE I.
    SELECT SINGLE * FROM SFLIGHT
                    WHERE
                      CARRID   = 'LH '      AND
                      CONNID   = '0400'     AND
                      FLDATE   = '19950228'.
    SEATSFREE = SFLIGHT-SEATSMAX - SFLIGHT-SEATSOCC.
    WRITE: / SFLIGHT-CARRID, SFLIGHT-CONNID,
             SFLIGHT-FLDATE, SEATSFREE.
    Variant 2
    SELECT [SINGLE [FOR UPDATE] | DISTINCT] s1 ... sn
    Effect
    The order, ABAP/4 Dictionary type and length of the columns of the result set are explicitly defined by the list s1 ... sn . Each si has the form
    ai or ai AS bi .
    Here, ai stands either for
    a field f of the database table or
    a aggregate print.
    bi is an alternative name for the i-th column of the result set.
    When using INTO CORRESPONDING FIELDS OF wa in the INTO clause , you can specify an alternative column name to assign a column of the result set uniquely to a column of the target area.
    An aggregate print uses an aggregate function to group together data from one or all columns of the database table. Aggregate prints consist of three or four components:
    An aggregate function immediately followed by an opening parenthesis DISTINCT (optional) The database field f A closing parenthesis
    All components of a print must be separated by at least one blank.
    The following aggregate functions are available:
    MAX Returns the greatest value in the column determined by the database field f for the selected lines. Specifying DISTINCT does not change the result. NULL values are ignored unless all values in a column are NULL values. In this case, the result is NULL .
    MIN Returns the smallest value in the column determined by the database field f for the selected lines. Specifying DISTINCT does not change the result. NULL values are ignored unless all values in a column are NULL values. In this case, the result is NULL .
    AVG Returns the average value in the column determined by the database field f for the selected lines. AVG can only apply to a numeric field. NULL values are ignored unless all values in a column are NULL values. In this case, the result is NULL .
    SUM Returns the sum of all values in the column determined by the database field f for the selected lines. SUM can only apply to a numeric field. NULL values are ignored unless all values in a column are NULL values. In this case, the result is NULL .
    COUNT Returns the number of different values in the column determined by the database field f for the selected lines. Specifying DISTINCT is obligatory here. NULL values are ignored unless all values in a column are NULL values. In this case, the result is 0
    COUNT( * ) Returns the number of selected lines. If the SELECT command contains a GROUP BY clause , it returns the number of lines for each group. The form COUNT(*) is also allowed.
    If ai is a field f , MAX( f ) , MIN( f ) or SUM( f ) , the corresponding column of the result set has the same ABAP/4 Dictionary format as f . With COUNT( f ) or COUNT( * ) , the column has the type INT4 , with AVG( f ) the type FLTP .
    If you specify aggregate functions together with one or more database fields in a SELECT clause, all database fields not used in one of the aggregate functions must be listed in the GROUP-BY clause . Here, the result of the selection is a table.
    If only aggregate functions occur in the SELECT clause, the result of the selection is a single record. Here, the SELECT command is not followed later by an ENDSELECT .
    Notes
    This variant is not available for pooled tables and cluster tables .
    If the SELECT clause contains a database field of type LCHAR or LRAW , you must specify the appropriate length field immediately before.
    Notes
    Performance
    Specifying aggregate functions excludes the use of SAP buffering .
    Since many database systems do not manage the number of table lines and therefore have to retrieve this at some cost, the function COUNT( * ) is not suitable for checking whether a table contains a line or not. To do this, it is best to use SELECT SINGLE f ... for any table field f .
    If you only want to select certain columns of a database table, you are recommended to specify a list of fields in the SELECT clause or to use a View .
    Examples
    Output all flight destinations for Lufthansa flights from Frankfurt:
    TABLES SPFLI.
    DATA   TARGET LIKE SPFLI-CITYTO.
    SELECT DISTINCT CITYTO
           INTO TARGET FROM SPFLI
           WHERE
             CARRID   = 'LH '       AND
             CITYFROM = 'FRANKFURT'.
      WRITE: / TARGET.
    ENDSELECT.
    Output the number of airline carriers which fly to New York:
    TABLES SPFLI.
    DATA   COUNT TYPE I.
    SELECT COUNT( DISTINCT CARRID )
           INTO COUNT FROM SPFLI
           WHERE
             CITYTO = 'NEW YORK'.
    WRITE: / COUNT.
    Output the number of passengers, the total weight and the average weight of luggage for all Lufthansa flights on 28.02.1995:
    TABLES SBOOK.
    DATA:  COUNT TYPE I, SUM TYPE P DECIMALS 2, AVG TYPE F.
    DATA:  CONNID LIKE SBOOK-CONNID.
    SELECT CONNID COUNT( * ) SUM( LUGGWEIGHT ) AVG( LUGGWEIGHT )
           INTO (CONNID, COUNT, SUM, AVG)
           FROM SBOOK
           WHERE
             CARRID   = 'LH '      AND
             FLDATE   = '19950228'
           GROUP BY CONNID.
      WRITE: / CONNID, COUNT, SUM, AVG.
    ENDSELECT.
    Variant 3
    SELECT [SINGLE [FOR UPDATE] | DISTINCT] (itab)
    Effect
    Works like SELECT [SINGLE [FOR UPDATE] | DISTINCT] s1 ... sn if the internal table itab contains the list s1 ... sn as ABAP/4 source code, and like SELECT [SINGLE [FOR UPDATE] | DISTINCT] * , if itab is empty. The internal table itab can only have one field which must be of type C and cannot be more than 72 characters long. itab must appear in parentheses and there should be no blanks between the parentheses and the table name.
    Note
    With this variant, the same restrictions apply as for SELECT [SINGLE [FOR UPDATE] | DISTINCT] s1 ... sn .
    Example
    Output all Lufthansa flight routes:
    TABLES: SPFLI.
    DATA:   FTAB(72) OCCURS 5 WITH HEADER LINE.
    REFRESH FTAB.
    FTAB = 'CITYFROM'. APPEND FTAB.
    FTAB = 'CITYTO'.   APPEND FTAB.
    SELECT DISTINCT (FTAB)
           INTO CORRESPONDING FIELDS OF SPFLI
           FROM SPFLI
           WHERE
             CARRID   = 'LH'.
      WRITE: / SPFLI-CITYFROM, SPFLI-CITYTO.
    ENDSELECT.
    check this one:
    http://www.sts.tu-burg.de/teaching/sap_r3/ABAP4/select.htm

  • Count of unique values in 7 columns

    Hey there…
    I have a Lookup table with 8 columns
    ID = unique ID
    U = Sunday,
    M = Monday
    T = Tues
    W = Weds
    R = Thur
    F = Fri
    S = Sat
    Each of the ‘day’ columns can have a value between 1 and 1150, looks like this
    ID U M T W R F S
    1 15 15 16 15 17 345 17
    What I am trying to find is a count of the deviation of each row… or how many of the days have different values
    So for the above example
    ID U M T W R F S COUNT
    1 15 15 16 15 17 345 17 4
    As there are 4 unique values in the week..
    15,16,17,345
    Any ideas on how that could be done in oracle? Stumped!

    Yep, pre-11g:
    CREATE TABLE temp (id INTEGER, col_1 INTEGER, col_2 INTEGER, col_3 INTEGER, col_4 INTEGER, col_5 INTEGER, col_6 INTEGER, col_7 INTEGER);
    INSERT INTO temp VALUES (1000, 1, 2, 3, 4, 5, 6, 7);
    INSERT INTO temp VALUES (1001, 7, 2, 3, 4, 5, 6, 7);
    INSERT INTO temp VALUES (1002, 1, 1, 1, 1, 1, 1, 1);
    SELECT * FROM temp
    ORDER BY id;
    SELECT id, COUNT (DISTINCT col)
      FROM (
    SELECT id, col_1 col FROM temp UNION
    SELECT id, col_2 FROM temp UNION
    SELECT id, col_3 FROM temp UNION
    SELECT id, col_4 FROM temp UNION
    SELECT id, col_5 FROM temp UNION
    SELECT id, col_6 FROM temp UNION
    SELECT id, col_7 FROM temp
    GROUP by id
    ORDER BY 1;
    Table dropped.
    Table created.
    1 row created.
    1 row created.
    1 row created.
            ID  COL_1  COL_2  COL_3  COL_4  COL_5  COL_6  COL_7
          1000      1      2      3      4      5      6      7
          1001      7      2      3      4      5      6      7
          1002      1      1      1      1      1      1      1
            ID COUNT(DISTINCTCOL)
          1000                  7
          1001                  6
          1002                  1

  • Prob. with finding the unique special characters

    Hi Friends,
    I have a table having special characters as data
    ex:
    š
    Š
    Ř
    Š
    ř
    Ř
    when i query for distinct (unique) data as "select distinct(entity) from tname;
    it results
    Š
    Ř
    I need unique values (upper and lower spsl charcters has different ascii) as
    š
    Š
    Ř
    ř
    Please help me to accomplish this task.
    Thanks
    Maha

    Have you tried
    select distinct entity, ascii(entity) from tname;Cheers
    Sarma.

  • Count Distinct over a Window

    Hi everyone,
    An analyst on my team heard of a new metric called a "Stickiness" metric. It basically measures how often users are coming to your website overtime.
    The definition is as follows:
    # Unique Users Today/#Unique users Over Last 7 days
    and also
    # Unique Users Today/#Unique users Over Last 30 days
    We have visit information stored in a table W_WEB_VISIT_F. For the sake of simplicity say it has columns VISIT_ID, VISIT_DATE and USER_ID (there are several more dimensional columns it has but I want to keep this exercise simple).
    I want to create an aggregate table called W_WEB_VISIT_A that pre-aggregates the three values I need per day: # Unique Users Today, #Unique users Over Last 7 days and #Unique users Over Last 30 days. The only way I can think of building the aggregate table is as follows
    WITH AGG AS (
    SELECT
    VISIT_DATE,
    USER_ID
    FROM W_WEB_VISIT_F
    GROUP BY
    VISIT_DATE,
    USER_ID
    select
    VISIT_DATE
    COUNT(DISTINCT USER_ID) UNIQUE_TODAY,
    (select count(distinct hist.USER_ID) from agg hist where hist.VISIT_DATE between src.VISIT_DATE - 6 and src.VISIT_DATE) SEVEN_DAYS,
    (select count(distinct hist.USER_ID) from agg hist where hist.VISIT_DATE between src.VISIT_DATE - 29 and src.VISIT_DATE) THIRTY_DAYS
    from agg
    group by visit_date
    The problem I am having is that W_WEB_VISIT_F has several million records in it and I can't get it the above query to complete. It ran over night and didn't complete.
    Is there a fancy 11g function I can use to do this for me? Is there a more efficient method?
    Thanks everyone for the help!
    -Joe
    Edited by: user9208525 on Jan 13, 2011 6:24 AM
    You guys are right. I missed the group by I had in the WITH Clause.

    Hi,
    Haven't used the windowing clause a lot, so I wanted to give a try.
    I made up some data with this query :create table t as select sysdate-dbms_random.value(0,10) visit_date, mod(level,5)+1 user_id
    from dual
    connect by level <= 20;Which gave me following rows :Scott@my10g SQL>select * from t order by visit_date;
    VISIT_DATE             USER_ID
    03/01/2011 13:17:10          1
    04/01/2011 05:30:30          4
    04/01/2011 08:08:13          5
    04/01/2011 14:42:24          3
    04/01/2011 20:20:58          3
    05/01/2011 17:29:24          2
    05/01/2011 17:40:20          4
    05/01/2011 18:32:56          2
    06/01/2011 04:12:53          5
    06/01/2011 08:59:18          2
    06/01/2011 09:04:26          3
    06/01/2011 10:14:20          1
    06/01/2011 14:22:54          1
    06/01/2011 19:39:04          1
    08/01/2011 14:44:18          5
    08/01/2011 21:38:04          5
    11/01/2011 04:56:05          4
    11/01/2011 18:52:29          2
    11/01/2011 23:57:30          4
    13/01/2011 07:24:22          3
    20 rows selected.I came up to that query :select
            v.*,
            case
                    when unq_l3d is null then -1
                    else trunc(unq_today/unq_l3d,2)
            end ratio
    from (
            select distinct trcdt, unq_today, unq_l3d
            from (
                    select
                    trcdt,
                    count(user_id)
                    over (
                            order by trcdt
                            range between numtodsinterval(1,'DAY') preceding and current row
                    ) unq_today,
                    count(user_id)
                    over (
                            order by trcdt
                            range between numtodsinterval(3,'DAY') preceding and current row
                    ) unq_l3d
                    from (
                            select distinct trunc(visit_date) trcdt, user_id from t
    ) v
    order by trcdtWith my sample data, it gives me :TRCDT                UNQ_TODAY    UNQ_L3D RATIO
    03/01/2011 00:00:00          1          1  1.00
    04/01/2011 00:00:00          4          4  1.00
    05/01/2011 00:00:00          5          6  0.83
    06/01/2011 00:00:00          6         10  0.60
    08/01/2011 00:00:00          1          7  0.14
    11/01/2011 00:00:00          2          3  0.66
    13/01/2011 00:00:00          1          3  0.33
    7 rows selected.where :
    - UNQ_TODAY is the number of distinct user_id in the day
    - UNQ_L3D is the number of distinct user_id in the last 3 days
    - RATIO is UNQ_TODAY divided by UNQ_L3D +(when UNQ_L3D is not zero)+
    It seems quite correct, but you would have to modify the query to fit to your needs and double-check the results !
    Just noticed that my query is all wrong*... must have been missing coffeine, or sleep.... but I'm still trying !
    Edited by: Nicosa on Jan 13, 2011 5:29 PM

  • Interactive Report Filter - Display Distinct Rows

    Is there a way to display only distinct rows once the filters are applied? Currently in my report, if the user selects only a subset of the columns available, then the rows appear to be duplicates.

    I have the same problem. I have been testing the "Group by" in the latest version of APEX, but it does not meet our needs. The current "Group by" only allows 3 columns. I need to report many columns. The preferred solution would be a "Distinct/Unique Option".
    Andre

  • Extracting unique records from two different tables record

    Hello,
    In the following code of two different tables www.testing.com exists in both tables. I want to compare two different columns of the two different tables to get unique records.
    SQL> select unique(videoLinks) from saVideos where sa_id=21;
    VIDEOLINKS
    www.testing.com
    SQL> ed
    Wrote file afiedt.buf
      1* select unique(picLinks) from saImages where sa_id=21
    SQL> /
    PICLINKS
    test
    test14
    www.hello.com
    www.testing.comThanks & best regards

    Unfortunatly you didn't mention the expected output. I guess it would be the one line
    "www.testing.com"
    in that case simply join the two tables.
    select *
    from saVideos v
    join saImages i on i.sa_id = v.sa_id and i.picLinks = v.videoLinks
    where v.sa_id=21;If needed then you could change the select list to retrieve only distinct values.
    select unique v.sa_id, v.videolinks
    from saVideos v
    join saImages i on i.sa_id = v.sa_id and i.picLinks = v.videoLinks
    where v.sa_id=21;I usually avoid distinct/unique whereever possible. This requires the database to do a sort and makes the query slow.
    Edited by: Sven W. on Feb 10, 2011 1:55 PM

  • How to tune the SQL & solve UNIQUE Contraint issue using without duplicates

    CREATE TABLE REL_ENT_REF
      ROLL_ENT        VARCHAR2(4 BYTE)              NOT NULL,
      ROLL_SUB_ENT    VARCHAR2(3 BYTE)              NOT NULL,
      ROLL_ENT_DESCR  VARCHAR2(50 BYTE),
      ENT             VARCHAR2(4 BYTE)              NOT NULL,
      SUB_ENT         VARCHAR2(3 BYTE)              NOT NULL,
      ENT_DESCR       VARCHAR2(50 BYTE)
    CREATE UNIQUE INDEX REL_ENT_REF_IDX_PK ON REL_ENT_REF
    (ROLL_ENT, ROLL_SUB_ENT, ENT, SUB_ENT);
    ALTER TABLE REL_ENT_REF ADD (
      CONSTRAINT REL_ENT_REF_IDX_PK
    PRIMARY KEY
    (ROLL_ENT, ROLL_SUB_ENT, ENT, SUB_ENT);
    TOTAL NUMBER OF RECORDS FOR TABLE REL_ENT_REF : 123542
    CREATE TABLE REL_COA_REF
      ACCT                    VARCHAR2(9 BYTE)      NOT NULL,
      ACCT_LVL                VARCHAR2(2 BYTE)      NOT NULL,
      ACCT_ID                 VARCHAR2(9 BYTE)      NOT NULL,
      REL_TYPE                VARCHAR2(10 BYTE)     NOT NULL,
      ACCT_TYPE               VARCHAR2(2 BYTE)      NOT NULL,
      ACCT_DESCR              VARCHAR2(43 BYTE),
      POST_ACCT               VARCHAR2(9 BYTE)      NOT NULL,
      POST_ACCT_TYPE          VARCHAR2(2 BYTE),
      POST_ACCT_DESCR         VARCHAR2(43 BYTE),
      SIGN_REVRSL             NUMBER
    CREATE INDEX REL_COA_REF_IDX_01 ON REL_COA_REF
    (ACCT_ID, REL_TYPE, POST_ACCT);
    CREATE UNIQUE INDEX REL_COA_REF_IDX_PK ON REL_COA_REF
    (ACCT_ID, ACCT, REL_TYPE, POST_ACCT);
    TOTAL NUMBER OF RECORDS FOR TABLE REL_COA_REF : 4721918
    CREATE TABLE REL_CTR_HIER_REF
      ENT           VARCHAR2(4 BYTE)                NOT NULL,
      SUB_ENT       VARCHAR2(3 BYTE)                NOT NULL,
      HIER_TBL_NUM  VARCHAR2(3 BYTE)                NOT NULL,
      HIER_ROLL     VARCHAR2(14 BYTE)               NOT NULL,
      HIER_CODE     VARCHAR2(14 BYTE)               NOT NULL,
      SUM_FLAG      VARCHAR2(14 BYTE)               NOT NULL,
      CTR_OR_HIER   VARCHAR2(14 BYTE)               NOT NULL,
      CTR_DETAIL    VARCHAR2(14 BYTE)               NOT NULL,
      CTR_DESCR     VARCHAR2(50 BYTE)
    CREATE INDEX REL_CTR_HIER_REF_IDX_01 ON REL_CTR_HIER_REF
    (HIER_TBL_NUM, HIER_ROLL, SUM_FLAG);
    CREATE UNIQUE INDEX REL_CTR_HIER_REF_IDX_PK ON REL_CTR_HIER_REF
    (ENT, SUB_ENT, HIER_TBL_NUM, HIER_ROLL, SUM_FLAG,
    CTR_DETAIL, CTR_OR_HIER, HIER_CODE);
    CREATE INDEX REL_CTR_HIER_REF_IDX_02 ON REL_CTR_HIER_REF
    (ENT, SUB_ENT, HIER_TBL_NUM, CTR_OR_HIER, SUM_FLAG,
    CTR_DETAIL);
    TOTAL NUMBER OF RECORDS FOR TABLE REL_CTR_HIER_REF : 24151811
    CREATE TABLE REL_TXN_ACT_CM
      ENT               VARCHAR2(4 BYTE),
      SUB_ENT           VARCHAR2(3 BYTE),
      POST_ACCT         VARCHAR2(9 BYTE),
      CTR               VARCHAR2(7 BYTE),
      POST_DATE         DATE,
      EFF_DATE          DATE,
      TXN_CODE          VARCHAR2(2 BYTE),
      TXN_TYPE          VARCHAR2(1 BYTE),
      TXN_AMOUNT        NUMBER(17,2),
      TXN_DESCR         VARCHAR2(46 BYTE),
      TXN_SOURCE        VARCHAR2(1 BYTE)
    CREATE INDEX REL_TXN_ACT_CM_IDX_01 ON REL_TXN_ACT_CM
    (ENT, SUB_ENT, POST_ACCT, POST_DATE, EFF_DATE,
    TXN_AMOUNT);
    CREATE INDEX REL_TXN_ACT_CM_IDX_PK ON REL_TXN_ACT_CM
    (ENT, SUB_ENT, CTR, POST_ACCT, POST_DATE,
    EFF_DATE, TXN_AMOUNT);
    TOTAL NUMBER OF RECORDS FOR TABLE REL_TXN_ACT_CM : 111042301
    CREATE TABLE REL_CLPR_TBOX_GL_TXN
      ORGANIZATION  VARCHAR2(10 BYTE)               NOT NULL,
      ACCOUNT       VARCHAR2(10 BYTE)               NOT NULL,
      APPLICATION   VARCHAR2(10 BYTE)               NOT NULL,
      AMOUNT        NUMBER(17,2)                    NOT NULL
    CREATE UNIQUE INDEX REL_CLPR_TBOX_GL_TXN_IDX ON REL_CLPR_TBOX_GL_TXN
    (ORGANIZATION, ACCOUNT, APPLICATION);
        DELETE FROM REL_CLPR_TBOX_GL_TXN;
        INSERT INTO REL_CLPR_TBOX_GL_TXN
          ORGANIZATION,
          ACCOUNT,
          APPLICATION,
          AMOUNT
        SELECT  --+ INDEX(T REL_TXN_ACT_CM_IDX_PK)
          SUBSTR(REL_CTR_HIER_REF.HIER_CODE, 1, 5) || '.....',
          TXN.POST_ACCT,
          'GL-' || SUBSTR(TXN.TXN_DESCR, 1, 3),
          SUM
            CASE
              WHEN TXN.TXN_CODE IN ('01', '21') THEN 1
                    WHEN TXN.TXN_CODE IN ('02', '22') THEN -1
                    ELSE 0
            END
            CASE
              WHEN REL_COA_REF.ACCT_TYPE IN ('01', '25', '30', '40', '90', '95') THEN 1
                    WHEN REL_COA_REF.ACCT_TYPE IN ('05', '10', '20', '35') THEN -1
                    ELSE 0
            END
            REL_COA_REF.SIGN_REVRSL
            TXN.TXN_AMOUNT
        FROM
          REL_TXN_ACT_CM REL_TXN
            INNER JOIN
          REL_CTR_HIER_REF
            ON
              REL_TXN.ENT = REL_CTR_HIER_REF.ENT AND
              REL_TXN.SUB_ENT = REL_CTR_HIER_REF.SUB_ENT AND
              REL_TXN.CTR = REL_CTR_HIER_REF.CTR_DETAIL
            INNER JOIN
          REL_COA_REF
            ON REL_TXN.POST_ACCT = REL_COA_REF.POST_ACCT
            INNER JOIN
          REL_ENT_REF
            ON
              REL_CTR_HIER_REF.ENT = REL_ENT_REF.ENT AND
              REL_CTR_HIER_REF.SUB_ENT = REL_ENT_REF.SUB_ENT
        WHERE
          REL_TXN.EFF_DATE BETWEEN L_MONTH AND LAST_DAY(L_MONTH) AND
          REL_CTR_HIER_REF.HIER_TBL_NUM = '001' AND
          REL_CTR_HIER_REF.SUM_FLAG = 'D' AND
          REL_CTR_HIER_REF.CTR_OR_HIER = REL_CTR_HIER_REF.CTR_DETAIL AND
          REL_CTR_HIER_REF.HIER_CODE BETWEEN 'AAA' AND 'ZZZ' AND
          REL_COA_REF.REL_TYPE = ' ' AND
          REL_COA_REF.ACCT_ID = 'ALPTER' AND
          REL_COA_REF.ACCT_LVL = '9' AND
          REL_ENT_REF.ROLL_ENT = '999' AND
          REL_ENT_REF.ROLL_SUB_ENT = '111'
        GROUP BY
          SUBSTR(REL_CTR_HIER_REF.HIER_CODE, 1, 5),
          REL_TXN.POST_ACCT,
          SUBSTR(REL_TXN.TXN_DESCR, 1, 3)
        HAVING
          SUM
            CASE
              WHEN REL_TXN.TXN_CODE IN ('01', '21') THEN 1
                    WHEN REL_TXN.TXN_CODE IN ('02', '22') THEN -1
                    ELSE 0
            END
            CASE
              WHEN REL_COA_REF.ACCT_TYPE IN ('01', '25', '30', '40', '90', '95') THEN 1
                    WHEN REL_COA_REF.ACCT_TYPE IN ('05', '10', '20', '35') THEN -1
                    ELSE 0
            END
            REL_COA_REF.SIGN_REVRSL
            REL_TXN.TXN_AMOUNT
          ) <> 0;
    [\CODE]
    While try to run the query(only select statement), it is taking around 3+ hours & while try to insert the same query in the table, getting error called ORA-00001: unique constraint (INSIGHT.CLPR_TBOX_GL_TXN_IDX) violated.
    [\CODE]
    How to tune & resolve this UNIQUE Contraint issue using without duplicates?

    Should the SELECT statement be returning duplicate rows? If you know that there are duplicate rows in the underlying tables, you could add a DISTINCT to the select. Which forces Oracle to do an extra sort which will slow down the insert. If you don't expect duplicate rows, you would need to figure out what join criteria is missing from your query and add that criteria.
    Justin

Maybe you are looking for