Count(*) function in select statement having group by condition

Hi
I would like to use count(*) in select statement having group by clause. say for example there is a state with a number of cities listed. I would like to get the count of cities for each state.
the sql stement is grouped by state and it is joined with 5 more tables.
Thanks
ps: ignore the previous post

Assuming there is one record per city per state, then
SELECT state,count(*)
FROM state_tbl
GROUP BY stateWill get one record per state with the number of cities in each state. If you want to join that result set to other tables you need to either create a view with that statement or use an in-line view viz.
SELECT c.cust_name,c.state,s.num_cities
FROM customers c,
     (SELECT state,count(*) num_cities
      FROM state_tbl
      GROUP BY state) s
WHERE c.state = s.stateTTFN
John

Similar Messages

  • Count(*) in select statement having group by clause

    Hi
    I would like to use count(*) in select statement having group by clause. say for example there is a state with a number of cities listed. I would like to get the count of cities for each state.
    the sql stement is grouped by city and it is joined with 5 more tables.
    Thanks

    I suspect you want to look into analytic functions (assuming you have a recent version of Oracle). asktom.oracle.com has numerous examples if you do a search.
    Justin

  • PL/SQL Function in Select statement

    Hi
    I am calling a function in select statement. The query works in Toad and PL/SQL developer except SQL plus and disconnecting Oracle connection.
    The error is “ERROR at line 1: ORA-03113: end-of-file on communication channel”.
    When I called the same query from BC4J View Object the error message is “java.sql.SQLException: No more data to read from socket”.
    Can any one advise me please?
    Thanks
    Srini

    Srini
    I've seen similar cases in the past with 9.2.0.x (x <= 5). What Oracle version are you using? It's worth checking the bug database (I can't just now - I don't have a valid support id in my current contract). And as Warren says, post your SQL query.
    HTH
    Regards nigel

  • Using java function in select statement

    Hi,
    I am trying to use java function in select statement.
    public class ClassA{
         private static String MyConst = "foo";
         public static String functionA(){
              return MyConst;
    in my query I have:
    select
         ClassA.functionA() AS id,
         groupId AS newID,
    from
         myChannel[now]
    ClassA is part of the application (no need to import).
    I get and error of Invalid Expression on ClassA.functionA().
    I also tried to declare the function in the processor element:
    <wlevs:processor id="proc">
         <wlevs:function function-name="A" exec-methode="functionA">
              <bean class="mtPackage.ClassA"/>
         </wlevs:function>
    <wlevs:processor>
    but then I get a different error in the processor XML file:  "An InvocationTargetException was encoutered while attemting to register the user defind function A. The message was null"
    What am I missing here?

    Hi,
    From the above description, you have tried two manners to call method functionA() in the user defined  class ClassA. One uses java cartridge manner directly and the other try to use user defined function manner.
    For the java cartridge manner, the following CQL query should work if the ClassA is really included in the OEP app. I have done similar test before, it works.
    select
         ClassA.functionA() AS id,
         groupId AS newID,
    from
         myChannel[now]
    For user defined function manner, I think two things you need to change:
    1. Need to declare the function in the EPN assembly file(under META-INF/spring/), not component configuration file(under META-INF/wlevs/). The following is an example:
    <wlevs:processor id="proc">
         <wlevs:function function-name="A" exec-methode="functionA">
              <bean class="mtPackage.ClassA"/>
         </wlevs:function>
    </wlevs:processor>
    2. Call the user defined function in the CQL query in the component configuration file under processor. For example:
    select A() from myChannel
    Regards,
    XiYing

  • Unable to call local function in select statement.

    Hi all,
    I am unable to call the local function in select statement in below scenario.
    DECLARE
    l_cnt NUMBER;
    FUNCTION FUN1 RETURN NUMBER
    AS
    BEGIN RETURN 2;
    END;
    BEGIN
    SELECT FUN1 INTO l_cnt FROM DUAL;
    DBMS_OUTPUT.PUT_LINE(l_cnt );
    END;
    /Any alternate way to call local function in select statement?
    Thanks
    Ram.

    Hi,
    Sorry, you can't call a locally defined function in a SQL statement, even if that SQL statement is in a PL/SQL block where the function is in scope.
    This applies to packages, also. If a function is not declared in the package spec, but only in the package body, then you can't call it from SQL statements in the package body.
    Why do you want a locally defined function? Why not a function defined outside the procedure?

  • Adding count from two select statements

    Hi,
    How to add counts from two select statements in a single SQL statement.
    For ex: I have
    SELECT COUNT(DISTINCT COL1) FROM table1
    and
    SELECT COUNT(DISTINCT COL2) FROM table2.
    I want to add the counts from these two sqls in a single select query. How to do this.
    Thanks & Regards,
    Sunil.

    select ((SELECT COUNT(DISTINCT COL1) FROM table1) + (SELECT COUNT(DISTINCT COL2) FROM table2)) as "total" from dual;
    regards,

  • How to pass rowtype argument to a function from select statement?

    Hi all!
    I have function that takes mytable%rowtype as in parameter. can I pass entire row of mytable to the function from select statement? kind of
    select myfunction(mytable.*) from mytable where ....
    Thanks in advance

    The function can be used in a SQL statement only if it accepts SQL types and returns SQL type. %ROWTYPE being PL/SQL construct and not a SQL datatype, can not be used in this context.
    http://download-west.oracle.com/docs/cd/B14117_01/server.101/b10743/datatype.htm#i2093

  • Select statement in if/else condition

    Hi i need to write a select statement in the if condition in pl/sql how can i write this
    example :
    if field_name not in (select statement) then
    Is this type of if condition is possible in pl/sql?
    thanks in advance for help.

    Qwerty wrote:
    here pick a job example salesman for ename ward, now i want to compare this job that is "salesman" with all the jobs which are before it. that is clerk in line 1 and salesman in line 2Define "before it". There is no order in relational tables. Only ORDER BY means ordered sets. Therefore there is no before/after without ORDER BY. Assuming ORDER BY empno, job count of same job title before empno:
    select  ename,
            job,
            count(*) over(partition by job order by empno) - 1 same_job_count_before_empno
      from  emp
    ENAME      JOB       SAME_JOB_COUNT_BEFORE_EMPNO
    SCOTT      ANALYST                             0
    FORD       ANALYST                             1
    SMITH      CLERK                               0
    ADAMS      CLERK                               1
    JAMES      CLERK                               2
    MILLER     CLERK                               3
    JONES      MANAGER                             0
    BLAKE      MANAGER                             1
    CLARK      MANAGER                             2
    KING       PRESIDENT                           0
    ALLEN      SALESMAN                            0
    ENAME      JOB       SAME_JOB_COUNT_BEFORE_EMPNO
    WARD       SALESMAN                            1
    MARTIN     SALESMAN                            2
    TURNER     SALESMAN                            3
    14 rows selected.To find job count of same job title as Ward has before Ward (by empno):
    SELECT  same_job_count_before_empno
      FROM  (
             select  ename,
                     count(*) over(partition by job order by empno) - 1 same_job_count_before_empno
               from  emp
      WHERE ename = 'WARD'
    SAME_JOB_COUNT_BEFORE_EMPNO
                              1SY.

  • OBIEE: Incorrect SQL - with count function uses ORDER BY instead GROUP BY

    I made a basic report that is a client count; I want to know how many clients the company have.
    But, when I run this report, OBIEE generates a ORDER BY sentence, instead a GROUP BY. Remember that I'm using count function, that is a agregation.
    The SQL generated was:
    select 'N0' as c1,
    count(*) as c2
    from
    (select distinct T1416.CLIENT_INTER_KEY as c1
    from
    (select *
    from prd.D_SERVICE where SOURCE_SYS in ('ARBOR','PPB') and DW_SERV_ST_ID in (100000003,100000009)) T1836,
    (select *
    from prd.D_CLIENT) T1416,
    (select *
    from prd.D_CUSTOMER_ACCOUNT where SOURCE_SYS In ('ARBOR','PPB')) T1515
    where ( T1416.DW_CLIENT_ID = T1515.DW_CLIENT_ID and T1515.DW_CUST_ACCT_ID = T1836.DW_CUST_ACCT_ID and T1836.MSISDN = '917330340' )
    ) D1
    order by c1
    The error that I receive is:
    "Query Status: Query Failed: [nQSError: 16001] ODBC error state: S1000 code: -1005018 message: [Sybase][ODBC Driver][Adaptive Server Anywhere]Illegal ORDER BY item Order Item: 'N0',
    -- (opt_OrderBy.cxx 429) .
    [nQSError: 16011] ODBC error occurred while executing SQLExtendedFetch to retrieve the results of a SQL statement."
    If I substitute ORDER BY with GROUP BY and test it in Sybase, Ithe query runs without any problem.
    select 'N0' as c1,
    count(*) as c2
    from
    (select distinct T1416.CLIENT_INTER_KEY as c1
    from
    (select *
    from prd.D_SERVICE where SOURCE_SYS in ('ARBOR','PPB') and DW_SERV_ST_ID in (100000003,100000009)) T1836,
    (select *
    from prd.D_CLIENT) T1416,
    (select *
    from prd.D_CUSTOMER_ACCOUNT where SOURCE_SYS In ('ARBOR','PPB')) T1515
    where ( T1416.DW_CLIENT_ID = T1515.DW_CLIENT_ID and T1515.DW_CUST_ACCT_ID = T1836.DW_CUST_ACCT_ID and T1836.MSISDN = '917330340' )
    ) D1
    group by c1
    Do you know why OBIEE generates this SQL??? Why uses, with a aggregation function, a ORDER BY and not a GROUP BY? How can I resolve this problem???
    Regards,
    Susana Figueiredo

    Verify your repository design and make sure that you have defined count aggregate on fact column. You would also need to define the content level of each dimension in fact table.

  • Functions in select statements - time consuming?!

    Hi All,
    I have a fairly complex view that uses a char based date (last business day) as one of the selection criteria. We have a report (based on the view) that needs to be run on a daily basis but the date will be different each day. I don't want to have to change the view every day to modify the date. The date is part of a larger text column and we're using a 'LIKE %dd/mm/yyyy%' to identify it in the select statement.
    I wrote a small function that returns the char based date with the %'s attached and have tested it on a small table. It works fine, however when I tried it on a larger table (50,000 rows) the difference between the response times of the following statements was unusable
    select count(*) from table where x like '%dd/mm/yyyy%' (420msec)
    and
    select count(*) from table where x like get_date_function (52 sec)
    I imagine that this is due to the function being called once for every row of the table. This isn't really going to be any good for me as the table I need to run the complex view against has nearly 750k rows and is growing every day.
    Any thoughts or suggestions as to how I can solve this problem (or work around it) would be much appreciated.
    rgds
    John

    Thanks Andrew,
    The rebuild the view on a daily basis seems to be the favorite solution at the moment. Its easy to do and will solve the problem, not elegantly but it will work.
    My understanding of calling functions inline from SQL is that the function will be called for every row that the SQL will reference regardless of what the function does.
    So if I wanted to do...
    select * from tablea where cola = sysdate-1
    on a table with 500 rows, sysdate would be called 500 times.
    If I was writing a procedure/package I would assign sysdate-1 to a variable and then do the select against the variable resulting in the sysdate function being called once and result in the query executing much faster.
    I can't help thinking that there must be a way of doing this, but then maybe I'm just being optimistic.
    I suppose what I am really trying to get is a way of calling a function once in some SQL regardless of how many rows are being referenced by the query.
    rgds
    John
    PS the code for the function is very simple, the performance hit is being caused by it being called once for every row in the table. The table it needs to run on is just under 1 million rows, which causes a significant lag ;).

  • Count() function with selective criteria?

    I'm struggling with what I would expect to be a fundamental reporting concept in CR.
    Suppose I have the following EMPLOYEE table:
    u2022 EMPLOYEE.ID
    u2022 EMPLOYEE.GENDER_CODE
    u2022 EMPLOYEE.MANAGER_FLAG
    I need to generate a statistical summary report containing the following:
    u2022 Total number of Employees
    u2022 Number of Male Employees
    u2022 Number of Management Employees
    This would be easy if I could just use a Count() function in the Function Workshop which
    contained selective criteria.  For example:  Count ({EMPLOYEE.GENDER_CODE} = 'M')
    But I can't figure out how to do this without getting a CR error message.
    Record Selection doesn't work, because I need the whole data set.
    Group Selection with Summaries doesn't work, because the gender and management
    attributes are not mutually exclusive.
    One solution that seems awkward to me is to create additional SQL commands in the
    Database Expert using COUNT(*) and WHERE criteria to get the number of Males
    and number of Managers.  But I have to believe that there is a better way.  Plus this
    approach causes problems elsewhere in my report.
    Am I missing something?
    Thanks,
    Bill

    Thanks Raghavendra!
    The good news is that I was able to create a "1 or 0" formula and then sum the resulting values.
    The bad news is that I'm only able to get this to work for part of my report.
    I am joining two tables.  As an example COMPANY and EMPLOYEE.
    I can use "1 or 0" formulas on all of the employee statistics.
    But I cannot do the same for company statistics, because the number of company records being assigned a 1 is being inflated by the join between the two tables.
    I have achieved a successful result by using Running Total Fields at the end of the report.
    But I want to place these summary statistics at the begining of my report.  (Such as Total Companies in the Western Region.)
    I tried to use "COMPANY.NAME = previous(COMPANY.NAME)" logic in my function, but then I was not allowed to summarize it.
    Any ideas?
    Thanks,
    Bill

  • Using function in select statement

    Hi,
    CREATE FUNCTION [dbo].[udf_testFunction] 
    @value int
    RETURNS int
    AS
    BEGIN
    -- Declare the return variable here
    declare @returnValue int
    set @returnValue = @value*2;
    return @returnValue;
    END
    GO
    create table #Temp
        EmpID int, 
        EmpName Varchar(50)
    insert into #Temp(EmpID,EmpName) values(1,'Name1');
    insert into #Temp(EmpID,EmpName) values(2,'Name2');
    insert into #Temp(EmpID,EmpName) values(3,'Name3');
    insert into #Temp(EmpID,EmpName) values(4,'Name4');
    insert into #Temp(EmpID,EmpName) values(5,'Name5');
    select EmpID,EmpName, [dbo].[udf_testFunction](EmpID), [dbo].[udf_testFunction](EmpID)*EmpID,[dbo].[udf_testFunction](EmpID)+2 from #Temp
    In the above select statement i used [dbo].[udf_testFunction]() function 3 times. But i want to use only once and reuse it.
    Something like 
    select EmpID,EmpName, testfunctionvalue,testfunctionvalue*EmpID,testfunctionvalue+2 from #Temp
    Please advise me.... Thanks in Advance...

    You can use this code: 
    WITH cte
    AS ( SELECT EmpID ,
    EmpName ,
    [dbo].[udf_testFunction](EmpID) AS testfunctionvalue
    FROM #Temp
    SELECT EmpID ,
    EmpName ,
    testfunctionvalue ,
    testfunctionvalue * EmpID ,
    testfunctionvalue + 2
    FROM cte
    But using scalar functions in select clause can hurt the performance. Please see this link: 
    SQL Server Scalar User Defined Function Performance
    T-SQL Articles
    T-SQL e-book by TechNet Wiki Community
    T-SQL blog

  • Function in select statement need to be called only for the last record.

    Select state,
    local,
    fun_state_loc_other_details(19) details
    from state_local
    where pm_key=19
    resuts:_
    State Local Details
    AP APlocal details1
    UP UPLocal details1
    MP MPLocal details1
    i) The above query returns 100 records
    ii) fun_state_loc_other_details is also getting called 100 times. But I want this function to be called only for the last record that is 100th record.
    is there any way to do that?

    Thanks amatu.
    One more small query. Can I do it on condition based.
    Select state,
    local,
    fun_state_loc_other_details(19) details
    from state_local
    where pm_key=19
    Like if one state it need to be called once.
    AP -- 50 records
    UP - 20 records
    MP -- 10 records.
    fyi: this record no. varies
    I want the function to be called for AP once, UP once, MP once.

  • Using TRIM function in select statement

    Hi All,
    I'm using the TRIM function in my select statement to eliminate the white spaces.
    But while using in select the TRIM function is not working in SQL*PLUS client(The query returns the white spaces also)
    Kindly provide some pointers regarding the issue.........
    I want to get only the data without the spaces in select statement
    Regards,
    Mohan

    Hi, Mohan,
    SQL*Plus always pads columns to make them line up nicely.
    If you have a column declared as VARCHAR2 (20), then SQL*Plus will normally display 20 characters for that column, even in the maximum actual length is, say, 5 (or even if the column always happens to be NULL).
    If you want the output to include only the actual data, without the padding that SQL*Plus adds, then concatenate all the columns into one big string column.
    People often do something like the following to generate a CSV file, with no exta spaces:
    SELECT       TO_CHAR (empno)
    || ',' || ename
    || ',' || job
    || ',' || TO_CHAR (deptno)
    || ',' || TO_CHAR (hiredate, 'DD-Mon-YYYY')     AS all_data
    FROM          scott.emp;

  • Using Column Name returned by function in SELECT statement

    Hi
    Output from my function (RETURN data type is VARCHAR2) is column name. I want to use it directly in my SELECT statement. Below is simplified example of this:
    --- Function
    CREATE OR REPLACE FUNCTION simple RETURN varchar2 IS
    BEGIN
    RETURN ‘my_column’;
    END simple;
    --- Select
    SELECT simple FROM my_table;
    This does not work. It seems that output from function is passed in quotation i.e.
    SELECT ‘my_column’ FROM my_table;
    So the output from SELECT is a list of rows populated with values my_table:
    COLUMN     simple
    ROW1     my_column
    ROW2     my_column
    ROW3     my_column
    Can please someone help me with this?

    I'm not sure I got you right.
    In standard SQL everything must be known at compile time. If not dynamic SQL is required, but is a costly operation (usually requires parsing before each execution) so it should better not be used when standard SQL can do it.
    I provided a design time example where a function returns the column name from the given the table name and column id for a varchar2 column data type to make things simple. Then a query string is constructed and executed dynymically to return all column values of the chosen table_name.column_name.
    SELECT simple FROM my_tableAt compile time the simple function return value is unknown (any varchar2 value would do) you already find out you get the (same) return value (i.e column name) for each table row => dynamic SQL needed to get the column values
    The purpose of function would be to rename all columns for provided table.The table name would be provided, right? If yes => dynamic SQL
    What is the function supposed to return the column name (where would the new name come from?), the column alias (which table column would be renamed to the new name?)
    The user could use the new_column name as the column alias name submitting the query.
    Is it possible to do this?Maybe () using a pipelined function (different data types - number,date, ... not cosidered yet) but your simple query;
    <tt>SELECT simple FROM my_table</tt>
    might look like:
    <tt>select my_column_value new_column_name from table(get_column_value(table_name,column_name))</tt>
    Sorry, no Database at hand to provide a specific example.
    Regards
    Etbin

Maybe you are looking for

  • Macbook's ability to use tv disappear overnight

    I have been using a HDMI cabel from my macbook pro to my tv. It has been working for the last month, and suddenly it doesn't work. My computer turns blue but the tv screen does not. Any one know what is wrong? I have checked all the cables to tv etc.

  • Question on BPM 11g Workflow Services

    Hi, There was no out of the box support feature which would enable the end users ( agents ) to fetch a work item one at a time from some queue . This allocation/fetch would be done on the basis of some algorithm ( SLA, Priority etc ) . We developed t

  • Scattered Home Page

    In Muse my home page scatters my images all over the place when I preview in browser, and Ctrl - to shrink the page. All other pages are fine, but they are laid out differently too. Are there some no no's in page layout?

  • Problem with stretching pattern on footer

    On the master page i have put a triangle on the bottom as my footer and placed on top a pattern. When I look in master page I see that the pattern stretches across the entire page as I require however when I upload the page it appears only partially.

  • Unwanted Cartesian join

    Hi there, Given the following schema: <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xdb="http://xmlns.oracle.com/xdb" targetNamespace="http://www.cognia.com" xmlns="http://www.cognia.com" elementF