Count Distinct Over Partition Syntax Error

Count(Distinct [field]) over (partition by [field2]) returns a syntax error at the key word distinct
Count(all [field]) over (partition by [field2]) compiles fine
I am writing a query to count the number of clients a sales rep has when the sales rep represents multiple companies (ad agency).  I need a count of the clients each company has and a distinct count that each rep has.  A client may be assigned to multiple companies.
Is a distinct count supported with partitions?

Until we wait for the full implementation of the OVER clause, you can
try something like this:
CREATE TABLE Foo (
fookey INT PRIMARY KEY,
company VARCHAR(30),
sales_rep VARCHAR(30),
client VARCHAR(30));
INSERT INTO Foo VALUES(1, 'ABC Corp.', 'Joe', 'Client1');
INSERT INTO Foo VALUES(2, 'ABC Corp.', 'Joe', 'Client2');
INSERT INTO Foo VALUES(3, 'ABC Corp.', 'Peter', 'Client2');
INSERT INTO Foo VALUES(4, 'DEF Corp.', 'Joe', 'Client1');
INSERT INTO Foo VALUES(5, 'DEF Corp.', 'Joe', 'Client3');
SELECT fookey, company, sales_rep, client,
MAX(rk1) OVER(PARTITION BY sales_rep) AS rep_distinct_client_cnt,
MAX(rk2) OVER(PARTITION BY company) AS company_distinct_client_cnt
FROM (
SELECT fookey, company, sales_rep, client,
DENSE_RANK() OVER(PARTITION BY sales_rep ORDER BY client) As rk1,
DENSE_RANK() OVER(PARTITION BY company ORDER BY client) As rk2
FROM Foo) AS F;
fookey company sales_rep client rep_distinct_client_cnt
company_distinct_client_cnt
1 ABC Corp. Joe Client1 3 2
2 ABC Corp. Joe Client2 3 2
3 ABC Corp. Peter Client2 1 2
4 DEF Corp. Joe Client1 3 2
5 DEF Corp. Joe Client3 3 2
Plamen Ratchev
http://www.SQLStudio.com

Similar Messages

  • [Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error

    Hi , i am trying to execute siple SP using JDBC-ODBC Bridge Driver
    Here my code :
    String dsn="Tritek1";
    String user="sa";
    String password="imcindia";
    Connection con1 = null;
    CallableStatement cstmt = null;
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
    con1=DriverManager.getConnection("jdbc:odbc:"+dsn,user,password);
    Statement st=con1.createStatement();
    st.execute("use dm0102d");
    st.execute("setuser 'dm01012'");
    cstmt = conObject.connection(" ?=Call dms_ex_get_folder_info(?,?,?)");
    cstmt.setString(1,folderType);
    cstmt.registerOutParameter(2,java.sql.Types.VARCHAR);
    cstmt.registerOutParameter(3,java.sql.Types.VARCHAR);     bFlag=cstmt.execute();
    Here my SP :
         Procedure Name          :     dms_ex_get_folder_info
         Input Parameter(s)          :     a. folder_type char(20)
         Return Parameter(s)     :     a. Recordset consist edit_mask and folder_type_code from folder_reference table / error
         Procedure Type          :     select
         Programmer          :     Prashanth Kumar M.
         Creation Date          :     12/20/2005 (20th Dec, 2005)
         Tables Accessed          :     folder_reference
         Revised               :
              Programmer:     Date:     Description:
              Prashanth Kumar M.      12/21/2005 Modified the script as per the approved program specifications.
         Test Query:
              Declare @edit_mask char(15)
              Declare @folder_type_code char(2)
              execute dms_ex_get_folder_info 'Policy Folder',@edit_mask output,@folder_type_code output
              Print 'Edit Mask : ' + @edit_mask
              Print 'Folder Type Code : ' + @folder_type_code
    CREATE PROCEDURE dms_ex_get_folder_info
         @folder_type char(20),
         @edit_mask char(15) output,
         @folder_type_code char(2) output
    AS
         BEGIN
              -- Check if the record for @folder_type exists or not.
              BEGIN
                   -- return the record from folder_reference
                   SELECT
                        @edit_mask= IsNull(edit_mask,''),
                        @folder_type_code = IsNull(folder_type_code,'')
                   FROM      folder_reference
                   WHERE
                        folder_decode = ltrim(rtrim(@folder_type))
                   -- return the error message
                   IF @@error <> 0
                        BEGIN
                             RAISERROR 100016 'Error in gettting the record from folder_reference table'
                             RETURN (@@error)
                        END
                   IF @edit_mask = '' AND @folder_type_code = ''
                        BEGIN
                             RAISERROR 100017 'No matching details in the folder_reference table'
                        RETURN (@@error)
                        END
              END
         END
    GO
    Here My Exception:
    java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error
         at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbc.SQLExecute(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(Unknown Source)
         at com.nyl.dms.bl.Folder.createFolder(Folder.java:121)
         at com.nyl.dms.bl.Folder.main(Folder.java:223)
    Any one can help me to overcome this problem . Thanks in advance.
    venkat

    Here's from one of those 10s of books.
    Quoted from JDBC 3.0 by Bernard Van Haecke:
    Stored procedures can return multiple result types because they can be composed of SQL statements that return diverse result types: resultsets and update counts (this includes special error codes).
    Now this doesn't sound very satisfactory. So I use Sybase since I don't have any other database at the moment, and write a simple stored procedure.
    CREATE proc testproc AS
    BEGIN
    -- My return code
    return 7
    END
    goThen a sample patchy buggy code to play around:
    import java.sql.*;
    public class ProcTesting {
        public static void main(String[] args) {
            String connUrl          = "jdbc:sybase:Tds:myserver:5150/dbinst";
            String userName         = "username";
            String password         = "password";
            Connection con          = null;
            CallableStatement stmt  = null;
            ResultSet rs            = null;
            String sql = "{? = call testproc}";
            try {
                Class.forName("com.sybase.jdbc2.jdbc.SybDriver").newInstance();
                con     = DriverManager.getConnection(connUrl, userName, password);
                stmt    = con.prepareCall(sql);
                stmt.registerOutParameter(1, Types.INTEGER);
                stmt.execute();
                System.out.println(stmt.getInt(1));
            } catch(Exception e) {
                e.printStackTrace();
            } finally {
                closeAll(con, stmt);
        public static void closeAll(Connection con, Statement stmt) {
            try {
                con.close();
            } catch(Exception e) {  }
            try {
                stmt.close();
            } catch(Exception e) {  }
    }Followed by:
    javac ProcTesting.java
    java -cp "%CLASSPATH%;C:\jarutils\jconn2.jar" ProcTesting
    Output:
    7
    Didn't you know this could be done?
    Happy new year, grandpa!

  • COUNT field incorrect or syntax error

    hi,
    PreparedStatement stmt = con.prepareStatement("Insert into uQuestions values(?,?)");
    stmt.setInt(1,2);
    //stmt.setString(2,s.trim());
    Reader rd=new StringReader(s.trim());
    stmt.setCharacterStream(2, rd );
    System.out.println( stmt.executeUpdate() );
    stmt.close();Result
    java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error
    In place of setCharacterStream If I use stmt.setString(2,s.trim()) then it works fine.
    Whats the problem there....

    I am using Java 6 already.That's what I said in my last post.
    setClob() and setCharacterStream() are used for
    NVARCHAR and NTEXT tyesLike I said, the API talks about using setCharacterStream for LONGVARCHAR types, are NVARCHAR and NTEXT LONGVARCHAR types?

  • COUNT field incorrect or syntax error while installing BO Xi3

    Hello
    I am trying to install Boxi3. The cms and audit dbs are all in sql database. The dbs and accounts are setup properly. However while installing, after I selected the CMS and Audit DBs, I am getting
    "Database access error. Reason [Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error."
    At the details the error is as below.
    Wed Jul 30 03:46:53 2008]     5220     192     trace message: loading libary succeeded
    [Wed Jul 30 03:46:53 2008]     5220     192     trace message: AuditDatabaseSubsystem::Init()
    [Wed Jul 30 03:46:53 2008]     5220     192     trace message: initializing subsystem succeeded
    [Wed Jul 30 03:46:53 2008]     5220     192     trace message: AuditDatabaseSubsystem::Connect()
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\DBConnectionManager.cpp:802): trace message: DBConnectionManager - Setting total target number of connections for pool 0 to 1.
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\SQLServerStatement.cpp:186): trace message: ExecDirect: SQL: SELECT * FROM APPLICATION_TYPE WHERE 0 = 1
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\SQLServerStatement.cpp:186): trace message: ExecDirect: SQL: SELECT * FROM AUDIT_EVENT WHERE 0 = 1
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\SQLServerStatement.cpp:186): trace message: ExecDirect: SQL: SELECT * FROM EVENT_TYPE WHERE 0 = 1
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\SQLServerStatement.cpp:186): trace message: ExecDirect: SQL: SELECT * FROM SERVER_PROCESS WHERE 0 = 1
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\SQLServerStatement.cpp:186): trace message: ExecDirect: SQL: SELECT * FROM AUDIT_DETAIL WHERE 0 = 1
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\SQLServerStatement.cpp:186): trace message: ExecDirect: SQL: SELECT * FROM DETAIL_TYPE WHERE 0 = 1
    [Wed Jul 30 03:46:53 2008]     5220     192     trace message: AuditDatabaseSubsystem::CheckDBCredentials()
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\AuditDatabaseSubsystem_impl.cpp:1197): trace message: AuditDatabaseSubsystem::CheckDBCredentialsOnTable(AUDIT_EVENT)
    [Wed Jul 30 03:46:53 2008]     5220     192     assert failure: (.\SQLServerDatabase.cpp:515). (0 : Unexpected database column type for Duration type is decimal).
    [Wed Jul 30 03:46:53 2008]     5220     192     assert failure: (.\SQLServerDatabase.cpp:515). (0 : Unexpected database column type for Event_Type_ID type is decimal).
    [Wed Jul 30 03:46:53 2008]     5220     192     assert failure: (.\SQLServerDatabase.cpp:515). (0 : Unexpected database column type for Error_Code type is decimal).
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\SQLServerStatement.cpp:162): trace message: Prepare: SQL: INSERT INTO AUDIT_EVENT (Duration, Error_Code, Event_ID, Event_Type_ID, Object_CUID, Server_CUID, Start_Timestamp, User_Name) VALUES(?, ?, ?, ?, ?, ?, ?, ?)
    [Wed Jul 30 03:46:53 2008]     5220     192     assert failure: (.\SQLServerStatement.cpp:699). (0 : Unsupported SQL Server data type for binding.).
    [Wed Jul 30 03:46:53 2008]     5220     192     assert failure: (.\SQLServerStatement.cpp:699). (0 : Unsupported SQL Server data type for binding.).
    [Wed Jul 30 03:46:53 2008]     5220     192     assert failure: (.\SQLServerStatement.cpp:699). (0 : Unsupported SQL Server data type for binding.).
    [Wed Jul 30 03:46:53 2008]     5220     192     assert failure: (.\AuditDatabaseSubsystem_impl.cpp:1344). (0 : no message).
    [Wed Jul 30 03:46:53 2008]     5220     192     assert failure: (.\AuditDatabaseSubsystem_impl.cpp:1344). (0 : no message).
    [Wed Jul 30 03:46:53 2008]     5220     192     assert failure: (.\AuditDatabaseSubsystem_impl.cpp:1344). (0 : no message).
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\SQLServerStatement.cpp:171): trace message: Prepared statement Execute
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\SQLServerDatabase.cpp:119): trace message: SQLServer error found:  ErrorMessage([Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error), ErrorCode(0)
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\AuditDatabaseSubsystem_impl.cpp:92): trace message: DBConnectionHolder - (AuditDB) - Caught retryable error with Code 0, Msg: [Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error  Number of retryable errors on this connection is 1
    [Wed Jul 30 03:46:53 2008]     5220     192     (.\dbutils.cpp:922): trace message: Caught DatabaseSubystem Error: Database access error. Reason [Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error.
    [Wed Jul 30 03:46:53 2008]     5220     192     trace message: AuditDatabaseSubsystem::Shutdown()
    This only happens for audit db and not for cms db. May I know what is the reason for this and how to resolve it?
    Thanks

    I am using Java 6 already.That's what I said in my last post.
    setClob() and setCharacterStream() are used for
    NVARCHAR and NTEXT tyesLike I said, the API talks about using setCharacterStream for LONGVARCHAR types, are NVARCHAR and NTEXT LONGVARCHAR types?

  • 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

  • Select over partition compilation error

    Forms [32 Bit] Version 10.1.2.0.2 (Production)!!
    Is it possible that select over partition is all right in a Record group while it is giving error in to trigger?
    Thanks in advance

    Triggers are compiled in forms so need to use only the features available to forms, which doesn't include all the new stuff in the database.
    Record groups are not compiled, they are parsed on the database so can include all database functionality. If you create a record group you can see immediately the source in v$sql, with bind variables replaced with :1, :2 etc.

  • COUNT(DISTINCT) WITH ORDER BY in an analytic function

    -- I create a table with three fields: Name, Amount, and a Trans_Date.
    CREATE TABLE TEST
    NAME VARCHAR2(19) NULL,
    AMOUNT VARCHAR2(8) NULL,
    TRANS_DATE DATE NULL
    -- I insert a few rows into my table:
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '110', TO_DATE('06/01/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '20', TO_DATE('06/01/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '110', TO_DATE('06/02/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '21', TO_DATE('06/03/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '68', TO_DATE('06/04/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '110', TO_DATE('06/05/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '20', TO_DATE('06/06/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Bill', '43', TO_DATE('06/01/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Bill', '77', TO_DATE('06/02/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Bill', '221', TO_DATE('06/03/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Bill', '43', TO_DATE('06/04/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Bill', '73', TO_DATE('06/05/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
    commit;
    /* I want to retrieve all the distinct count of amount for every row in an analytic function with COUNT(DISTINCT AMOUNT) sorted by name and ordered by trans_date where I get only calculate for the last four trans_date for each row (i.e., for the row "Anna 110 6/5/2005 8:00:00.000 PM," I only want to look at the previous dates from 6/2/2005 to 6/5/2005 and get the distinct count of how many amounts there are different for Anna). Note, I cannot use the DISTINCT keyword in this query because it doesn't work with the ORDER BY */
    select NAME, AMOUNT, TRANS_DATE, COUNT(/*DISTINCT*/ AMOUNT) over ( partition by NAME
    order by TRANS_DATE range between numtodsinterval(3,'day') preceding and current row ) as COUNT_AMOUNT
    from TEST t;
    This is the results I get if I just count all the AMOUNT without using distinct:
    NAME     AMOUNT     TRANS_DATE     COUNT_AMOUNT
    Anna 110 6/1/2005 8:00:00.000 PM     2
    Anna 20 6/1/2005 8:00:00.000 PM     2
    Anna 110     6/2/2005 8:00:00.000 PM     3
    Anna 21     6/3/2005 8:00:00.000 PM     4
    Anna 68     6/4/2005 8:00:00.000 PM     5
    Anna 110     6/5/2005 8:00:00.000 PM     4
    Anna 20     6/6/2005 8:00:00.000 PM     4
    Bill 43     6/1/2005 8:00:00.000 PM     1
    Bill 77     6/2/2005 8:00:00.000 PM     2
    Bill 221     6/3/2005 8:00:00.000 PM     3
    Bill 43     6/4/2005 8:00:00.000 PM     4
    Bill 73     6/5/2005 8:00:00.000 PM     4
    The COUNT_DISTINCT_AMOUNT is the desired output:
    NAME     AMOUNT     TRANS_DATE     COUNT_DISTINCT_AMOUNT
    Anna     110     6/1/2005 8:00:00.000 PM     1
    Anna     20     6/1/2005 8:00:00.000 PM     2
    Anna     110     6/2/2005 8:00:00.000 PM     2
    Anna     21     6/3/2005 8:00:00.000 PM     3
    Anna     68     6/4/2005 8:00:00.000 PM     4
    Anna     110     6/5/2005 8:00:00.000 PM     3
    Anna     20     6/6/2005 8:00:00.000 PM     4
    Bill     43     6/1/2005 8:00:00.000 PM     1
    Bill     77     6/2/2005 8:00:00.000 PM     2
    Bill     221     6/3/2005 8:00:00.000 PM     3
    Bill     43     6/4/2005 8:00:00.000 PM     3
    Bill     73     6/5/2005 8:00:00.000 PM     4
    Thanks in advance.

    you can try to write your own udag.
    here is a fake example, just to show how it "could" work. I am here using only 1,2,4,8,16,32 as potential values.
    create or replace type CountDistinctType as object
       bitor_number number,
       static function ODCIAggregateInitialize(sctx IN OUT CountDistinctType) 
         return number,
       member function ODCIAggregateIterate(self IN OUT CountDistinctType, 
         value IN number) return number,
       member function ODCIAggregateTerminate(self IN CountDistinctType, 
         returnValue OUT number, flags IN number) return number,
        member function ODCIAggregateMerge(self IN OUT CountDistinctType,
          ctx2 IN CountDistinctType) return number
    create or replace type body CountDistinctType is 
    static function ODCIAggregateInitialize(sctx IN OUT CountDistinctType) 
    return number is 
    begin
       sctx := CountDistinctType('');
       return ODCIConst.Success;
    end;
    member function ODCIAggregateIterate(self IN OUT CountDistinctType, value IN number)
      return number is
      begin
        if (self.bitor_number is null) then
          self.bitor_number := value;
        else
          self.bitor_number := self.bitor_number+value-bitand(self.bitor_number,value);
        end if;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateTerminate(self IN CountDistinctType, returnValue OUT
      number, flags IN number) return number is
      begin
        returnValue := 0;
        for i in 0..log(2,self.bitor_number) loop
          if (bitand(power(2,i),self.bitor_number)!=0) then
            returnValue := returnValue+1;
          end if;
        end loop;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateMerge(self IN OUT CountDistinctType, ctx2 IN
      CountDistinctType) return number is
      begin
        return ODCIConst.Success;
      end;
      end;
    CREATE or REPLACE FUNCTION CountDistinct (n number) RETURN number 
    PARALLEL_ENABLE AGGREGATE USING CountDistinctType;
    drop table t;
    create table t as select rownum r, power(2,trunc(dbms_random.value(0,6))) p from all_objects;
    SQL> select r,p,countdistinct(p) over (order by r) d from t where rownum<10 order by r;
             R          P          D
             1          4          1
             2          1          2
             3          8          3
             4         32          4
             5          1          4
             6         16          5
             7         16          5
             8          4          5
             9          4          5buy some good book if you want to start at writting your own "distinct" algorythm.
    Message was edited by:
    Laurent Schneider
    a simpler but memory killer algorithm would use a plsql table in an udag and do the count(distinct) over that table to return the value

  • Syntax error Creating Transparent Partition in MaxL

    Hello,
    I'm trying to create a simple transparent partition (no mapping needed, just using all the 3 dimensions and descendants in the source database to the target database. I'm getting a syntax error, I went through the MaxL naming conventions and also tried a couple of diffferent things but to no avail. Please help as to what the error might be:
    My code is as below. The error I get is: Getting a syntax error near '@IDESCENDANTS("Accounts"), @IDESCENDANTS("Products"),@IDESCENDANTS("Market)
    Code:
    create transparent partition student8.coke area '@IDESCENDANTS("Accounts"), @IDESCENDANTS("Products"),@IDESCENDANTS("Market")' sourceArea to student8.cokepart at lab01 as essadmin identified by 'password' area '@IDESCENDANTS("Accounts"), @IDESCENDANTS(Products), @IDESCENDANTS("Market")' targetArea;

    Nobody replied to this, but actually the error was the double quotes on Accounts, Products and Market.

  • Discoverer Plus - Lag / Over / Partition By / Order By (Conditional Syntax)

    Good morning everybody
    I have created the following syntax in Oracle Discoverer Plus and it works amazingly. However, I have a single problem.
    This syntax gives me the comparison of two values (for instance: Jan.2010 values & Feb.2010 values). But it does not give me the value of all of the new records (for instance: if there is no values in Jan.2010, then it will not give me the value of Feb.2010). Hence, my report excludes all of the new records values.
    If I am not mistaken, the below formulla will not be changed, but it needs some conditional syntax:
    1. Compare syntax: if there is two similar records; and
    2. Give the values of all the new records without any change in thier values
    *(Amount-LAG(Amount,1)OVER(PARTITION BY "Sequence Number"ORDER BY "Sequence Number ASC))*
    Thank very much in advance.
    Mr. Zuhair Fardan
    Kingdom of Bahrain
    Email: [email protected]

    Zuhair,
    change,
    (Amount-LAG(Amount,1)OVER(PARTITION BY "Sequence Number"ORDER BY "Sequence Number ASC)){code}
    to
    {code}
    (Amount-LAG(Amount,1,0)OVER(PARTITION BY "Sequence Number" ORDER BY "Sequence Number ASC))Note the extra zero in LAG(Amount,1,0). That's the default return value if nothing is found.
    As it is you are subtracting null from the amount and getting null.
    Hope that is helpful.
    - James

  • 1086  Syntax Error (on Counter.fla)

    Can anyone elaborate as to why I am getting an error with
    this "counter script" (counts down Years, Months, Days, Hours,
    Minutes, Seconds)? The error is "
    1086: Syntax error: expecting semicolon before months" (Line
    50), but after doing research on the error number and looking at
    the actual error line, it appears that it may be something other
    which I am not seeing?
    HERE is the Action Script I am using:
    this.addEventListener(Event.ENTER_FRAME,onEF);
    function onEF(evt:Event):void {
    var today:Date = new Date();
    var currentYear = today.getFullYear();
    var currentTime = today.getTime();
    var targetDate:Date = new Date(2011,10,16);
    var targetTime = targetDate.getTime();
    if (targetTime - currentTime > 0) {
    var timeLeft = targetTime - currentTime;
    } else {
    var timeLeft = currentTime - targetTime;
    var sec = Math.floor(timeLeft/1000);
    var min = Math.floor(sec/60);
    var hrs = Math.floor(min/60);
    var days = Math.floor(hrs/24);
    var months = Math.floor((H+L-7*M+114)/31);
    var years = Math.floor(days/365);
    sec = String(sec % 60);
    if (sec.length < 2) {
    sec = "0" + sec;
    min = String(min % 60);
    if (min.length < 2) {
    min = "0" + min;
    hrs = String(hrs % 24);
    if (hrs.length < 2) {
    hrs = "0" + hrs;
    days = String(days);
    if (days.length < 2) {
    days = "0" + days;
    months = String(months % 12);
    if (months.length < 2) {
    months = "0" + months;
    years = String(years);
    if (years.length < 2) {
    years = "0" + years;
    var counter:String = years + ":" months + ":" days + ":" +
    hrs + ":" + min + ":" + sec;
    time_txt.text = counter;
    }

    Thanks,
    kglad, for the quick and helpful response...
    I can't believe I didn't see that!
    Seems now I am getting another error on Line 22 -
    1120: Access of undefined property H, L, and M.
    Trying to correct that but if you have a better solution
    please feel free to share...
    Thanks again, regardless!
    A.J.

  • Group by count distinct

    mytable
    id | yy
    1 | 78
    2 | 78
    3 | 78
    3 | 79
    3 | 79
    4 | 79
    5 | 79
    5 | 80
    Desired output:
    yy | id_count
    78 | 3
    79 | 2
    80 | 0
    Following query doesn't work, as it doesn't take into account that id was already counted
    select yy, count(distinct id) as id_count
    from mytable
    group by yy
    --output
    yy | id_count
    78 | 3
    79 | 4
    80 | 1
    Hope this makes sense.
    Ideas?

    Hi,
    You only want to count each id once, with the first (that is, lowest) yy: is that right?
    Here's one way:
    WITH     got_r_num    AS
         SELECT  id
         ,     yy
         ,     ROW_NUMBER () OVER ( PARTITION BY  id
                                   ORDER BY          yy
                           ) AS r_num
         FROM    my_table
    SELECT       yy
           COUNT ( CASE
                      WHEN  r_num = 1
                    THEN  id
                  END
              )     AS id_cnt
    FROM       got_r_num
    GROUP BY  yy
    ORDER BY  yy
    ;Doing anything for the first of each id is probably a job for "ROW_NUMBER () OVER (PARTITION BY id ...)".

  • Row Number() over partition by Order by in OBIEE Physical SQL

    Hi ,
    I created a OBIEE report in Dev using Answers. When I move the same report to Live, the count of rows was more in Live environment when compared to Dev.
    The objects count is same in both Dev and Production.
    WheniI verified the log file, I found that the Physical SQL in test has
    ROW_NUMBER ()
    OVER
    PARTITION BY c1, c4, c5 order by c1,c4,c5) whereas the physical SQL in Production has
    ROW_NUMBER ()
    OVER
    PARTITION BY c1, c4, c5, c8,c9 order by c1,c4,c5,c8,c9)
    How this Partiton is done in OBIEE. I have just copied the report from catalog and moved to production.There is no changes in report.
    Whether there are any settings to control it? HOw OBIEE does this Row Number() Partiton ? How can get this similiar to Test?
    Please help!
    Thanks
    Johnny

    Hi Saichand,
    The links were helpful. But i am not getting how it is working in test and not in live.
    I found one difference while deploying . The column names of the object both in Test and Production had spaces.For E.g: Full Name
    When this column Full Name is pulled to the repsository in test , it automatically put double quotes for the column names in the physical sql when it hits the database.
    But, In production , when I pulled the column the report gave error as Invalid Identifier since OBIEE generated column name as Full Name without double quotes.
    Then I changed the column in Phyiscal Layer repository by having double Quotes for all columns. Afte that report worked fine.
    Whether this has caused any issue in Row Partition.
    Is there any setting to have column name in Double Quotes ?
    Thanks,
    Johnny

  • SUM OVER PARTITION BY condition?

    I have a piece of SQL similar to:
    SELECT person,
    amount,
    type,
    SUM(amount) OVER (PARTITION BY person) sum_amount_person
    FROM table_a
    What I would like to be able to do is use a conditional PARTITION BY clause, so rather than partition and summing for each person I would like to be able to sum for each person where type = 'ABC'
    I would expect the syntax to be something like
    SELECT person,
    amount,
    type,
    SUM(amount) OVER (PARTITION BY person WHERE type = 'ABC') sum_amount_person
    FROM table_a
    Is this possible? Or am I missing a much simpler solution?
    Richard

    The proposed query does not compile on my Windows Oracle 9.2.0.5 or 10.1. This could be generated by the ambiguty introduced by DECODE in the evaluation of query (does it filter the selected rows, or the rows summarized for each selected row, or both?).
    I propose two alternatives. The requirements are not specific enough to allow me to choose between them.
    SQL> SELECT * FROM table_a ORDER BY 1, 3;
    PERSON         AMOUNT TYP
    john               12 abc
    john                8 abc
    john               20 def
    mike               15 abc
    mike               30 ghi
    steve              30 abc
    6 rows selected.
    SQL> SELECT person,
      2  amount,
      3  type,
      4  SUM(decode(type, 'ABC',amount, to_number(NULL)) OVER (PARTITION BY person) sum_amount_person
      5  FROM table_a;
    SUM(decode(type, 'ABC',amount, to_number(NULL)) OVER (PARTITION BY person) sum_amount_person
    ERROR at line 4:
    ORA-30483: window  functions are not allowed here
    SQL> SELECT person,
      2  amount,
      3  type,
      4  CASE type WHEN 'abc' THEN SUM(amount) OVER (PARTITION BY person) END sum_amount_person
      5  FROM table_a;
    PERSON         AMOUNT TYP SUM_AMOUNT_PERSON
    john               12 abc                40
    john               20 def
    john                8 abc                40
    mike               15 abc                45
    mike               30 ghi
    steve              30 abc                30
    6 rows selected.
    SQL> SELECT person,
      2  amount,
      3  type,
      4  CASE type WHEN 'abc' THEN SUM(amount) OVER (PARTITION BY person, type) END sum_amount_person
      5  FROM table_a;
    PERSON         AMOUNT TYP SUM_AMOUNT_PERSON
    john               12 abc                20
    john                8 abc                20
    john               20 def
    mike               15 abc                15
    mike               30 ghi
    steve              30 abc                30
    6 rows selected.

  • (NOLOCK) is giving syntax error

    Hi,
    I have query which runs properly in 1 server and in the other server it gives syntax error because of (NOLOCK).
    When i remove (NOLOCK) its working fine.
    my query is a big one...
    But it is something like
    INSERT INTO @abc
    SELECT a.id,SUM(b.count) FROM
    (SELECT DISTINCT id FROM table1 (NOLOCK)) AS a
    INNER JOIN Table2 (NOLOCK) AS b
    GROUP BY a.id
    It is giving syntax error at only one (NOLOCK) that is near Table2 in one server and in other server it works fine...
    Both the server versions are exactly same...
    What is the reason?

    First, it is generally a bad idea to post a follow-up "me, too" response to an old and answered question.  Fewer people will look at an answered question generally. 
    Next, the reason this thread provides no information about the original problem and the solution is because the complete problem was not posted.  If your query generates an error message, it is important to see the complete and actual error message.
    Given the conversation, it is likely that there was a syntax error in the various statements that OP tried and it was a happy accident that the removal of the hint caused the error to go away. 
    Lastly one should refrain from using hints generally.  For some unfathomable reason there is a myth that it is a good practice to use the nolock hint. 

  • Query rewrite for COUNT(DISTINCT)

    Hi,
    I am having fact table with different dimension keys.
    CREATE TABLE FACT
    TIME_SKEY NUMBER
    REGION_SKEY NUMBER,
    AC_SKEY NUMBER
    I need to take COUNT(DISTINCT(AC_SKEY) for TIME_SKEY and REGION_SKEY. There are oracle dimension defined for time and region which are using TIME_SKEY and REGION_SKEY. I have created MV with query rewrite with COUNT(DISTINCT) but it is not using dimension if I am using any other level and MV can't be fast refreshed as it was build using COUNT(DISTINCT).
    CREATE MATERIALIZED VIEW AC_MV
    NOCACHE
    NOLOGGING
    NOCOMPRESS
    NOPARALLEL
    BUILD IMMEDIATE
    REFRESH COMPLETE ON DEMAND
    WITH PRIMARY KEY
    ENABLE QUERY REWRITE
    AS
    SELECT
    TIME_SKEY ,
    REGION_SKEY,
    COUNT (DISTINCTAC_SKEY)
    FROM FACT
    GROUP BY TIME_SKEY, REGION_SKEY;
    Query used to retrieve data is as below
    SELECT TIME_SKEY, COUNT(DISTINCT AC_SKEY) OVER (PARTITION BY TIME_SKEY) UNIQ_AC, COUNT(DISTINCT AC_SKEY) OVER () UNIQ_AC1
    FROM FACT;
    There can be other queries based on time / region dimension.
    Can you please provide help in solving above issue?
    Thanks,
    Pritesh

    What version of the Oracle database?

Maybe you are looking for

  • Hard drive failed, now I need to re-purchase iTune's library

    My father's hard drive failed and now his iTune's library is gone. I have two questions. 1. How can I buy a list of songs from the iTune's music store? I want to avoid re-purchasing individual songs and albums; it will take forever. 2. Is there a val

  • Rated song in my iphone/ipad does not show in itune

    hello i had rated som song as one star in my iphone, so when i connect to itunes, the rating should show, [when i select the music of my iphone in itunes] i used to have it in old release but now i dont know why does not show . i even made smart list

  • Timeline

    Hello I don't see any tracks in my timeline and cant drag and drop

  • RE:  PHOTOSHOP CC - MENU ITEM EXPLANATIONS

    1)  Where can I find a very basic, very in depth discussion of of all menu items?   There are so many that do not seem to be covered in any of the tutorials - such as "Image" > "Mode" > "8, 16, 32 Bit/Channel".   That's just an example.  Even Fundame

  • Sizing of still images for use in Premiere Pro editing.

    I use Premiere Pro 5.5. I use format: AVCHD 1080i25(50i) Anamorphic for my editing (I have a Canon Legria Camera). My current stills are resized to 800x 600. When I insert in to the sequence and play it, they fall outside the safety margins. I read t