Query Count of rows

Hi Everyone,
I have a table Table1
Table1: ID, Name, Sales, Time
Sample data:
1, Loo, Y, 20-JUL-09 01.20.17.000000000 PM
2, Rey, Y, 20-JUL-09 01.20.17.000000000 PM
1, Loo, Y, 20-JUL-09 01.20.17.000000000 PM
1, Loo, Y, 20-JUL-09 01.20.17.000000000 PM
3, Bon, Y, 20-JUL-09 01.20.17.000000000 PM
1, Loo, Y, 19-JUL-09 01.20.17.000000000 PM
I want the result as:
1, 3
2, 1
3, 1
i.e employee with id 1 and count of his apperaince in the table where data is 20-JULY-09
Any suggestions and inputs are appreciated.
Thanks
Kasi

Hi,
user10651875 wrote:
Thanks that worked.
If i want to change the query to get the ID which is having a count > 20 keeping all the other clauses, what should i modify?Do you mean you only want to diplay rows where count>20 (if any)?
Add a HAVING clause, immediately after the GROUP BY clause:
SELECT    id
,       COUNT (*)     AS cnt
FROM       table1
WHERE       TRUNC (time)     = DATE '2009-07-20'
GROUP BY  id
HAVING       COUNT (*)     > 20;HAVING is similar to WHERE, but WHERE is evaluated before aggregate functions (like COUNT in this example) are compute. HAVING is evaluated after the aggregate functions are computed, therefore, you can use them in the HAVING clause. (In fact, you should never have a HAVING clause that doesn't use aggregate functions.)

Similar Messages

  • Need Query to that generate count of rows of all tables

    Hi
    i need a query which gives the result of no.of rows in talbe and coresponding table name.
    And then i need to compare the same with other DB schema
    Thanks in advance

    Hi User,
    We can also get the count of rows for all the tables associated with a User, we can create a custom function which
    uses the table name to return results.
      CREATE OR REPLACE FUNCTION TAB_ROWS_CNT (TAB_NAME IN VARCHAR2)
       RETURN NUMBER
    AS
       TAB_CNT   NUMBER :=0;
    BEGIN
       EXECUTE IMMEDIATE 'select count(*) from ' || TAB_NAME
          INTO TAB_CNT;
       RETURN TAB_CNT;
    END;And query,
    SELECT TABLE_NAME, TAB_ROWS_CNT (TABLE_NAME) ROW_CNT
      FROM USER_TABLES;Which gets us the count of Individual Tables for a user.
    This is an just that we can do in this way also. But, use which is optimal.
    Thanks,
    Shankar

  • Count all rows of a Database table

    I want to count all the rows of a table.
    I have made correctly the connection with the database and all the other things (make a statement, make the query and the resultSet), I use the MySQL server v4.0.17
    Here is the code I use:
    int count=0;
    String temp=null;
    String query = "SELECT COUNT(*) FROM customers";//customers is my Database Table
    try {
    rs = stmt.executeQuery(query);
    }//end try
    catch(Exception exc) {
    createFeatures.PlayErrorSound(registerRenter);
    Optionpane.showMessageDialog(registerRenter,
    "MESSAGE", "ERROR", JOptionPane.ERROR_MESSAGE);
    }//end catch
    try {
    while(rs.next()) {
    count++; //I use this variable in order to count the rows because the resultSet doesn't tell me the answer
    countLine=rs.getInt(1);
    }//end while
    }//end try
    catch(Exception exc) {
    createFeatures.PlayErrorSound(registerRenter);
    Optionpane.showMessageDialog(registerRenter,
    "MESSAGE", "ERROR", JOptionPane.ERROR_MESSAGE);
    }//end catch
    count=count++; //i increase it aggain because if the rows are initial 0 i want to make it 1
    temp = String.valueOf(count);//i use this command in order to display the result into a jtextfield
    Any help is appreciated!!!!!

    This program will work just fine against mysql:
    mport java.util.*;
    import java.io.*;
    import java.sql.*;
    public class Test {
    public static void main(String []args) {
    String url= "jdbc:mysql://localhost/adatabase";
    String query = "select count(*) from foo2";
    String createQuery="create table foo2(f1 int)";
    String dropQuery="drop table foo2";
    String insertQuery="insert into foo2 values(1)";
    Properties props = new Properties();
    props.put("user", "auser");
    props.put("password", "xxxxx");
    try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    System.out.println("Connecting to the msql server");
    Connection con = DriverManager.getConnection(url, props);
    Statement stmt = con.createStatement();
    try {
    stmt.executeUpdate(dropQuery);
    } catch(SQLException e) {}
    stmt.executeUpdate(createQuery);
    stmt.executeUpdate(insertQuery);
    stmt.executeUpdate(insertQuery);
    PreparedStatement pstmt = con.prepareStatement(query);
    System.out.println("***Executing a select");
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()) {
    System.out.println("RowCount="+ rs.getString(1));
    rs.close();
    pstmt.close();
    stmt.close();
    con.close();
    } catch(Exception e) {
    System.out.println(e.getMessage());
    }

  • Count MySQL rows based off Value in Dynamic Table

    Greetings all. I have 2 MySQL tables; 1 that contains the names of my classes.(Class A, Class, B, etc.) and 1 table that contains the names of students in each Class (for example Class A: John Doe; Class A: Susie Smith.; Class B: Jane Doe). In the 2nd table the Class name is in its own column and the student's name is in a 2nd column.
    I currently have a dynamic repeating table that lists the names of all of the classes from the 1st table. What I'm trying to do is add a second column to this repeating dynamic table that lists the number of students in each class. For example; Row 1 of the dynamic table would say "Class A | 5; Class B | 3; Class C | 7, etc.). The dynamic table works perfectly to list the class names. For the life of me I can't figure out how to perform a count for each class to insert in the repeating table. I will be adding more Classes which as why I'm trying to set up the counting query dynamically. So far I have only been able to figure out how to count the total rows in the 2nd table, or count the rows with a specified class name. Any advice or guidance on how to count the number of rows in the 2nd MySQL table based off the class name in the repeating table is much appreciated. Thank you for any and all help. Have a great day.

    Select count(*), Class from MyTable
    Group by Class
    Time to learn about SQL:
    http://www.w3schools.com/sql/sql_intro.asp

  • The biggest count of rows of sys tables

    Hii ??
    I want to learn how can I find the biggest count of rows of sys tables or
    which table has around 900000 records on sys user database oracle 10g??

    Hello;
    What purpose would knowing the row count in tables owned by SYS serve ? The query below will give you a fair idea of row counts in tables owned by SYS assuming that statistics have been recently gathered for these tablesselect table_name,num_rows from dba_tables where owner='SYS';Varad

  • Paging and count of rows

    Hi,
    I have a procedure doing paging and returning the count of rows:
    As you see I used 2 select, one for paging and one for getting total row counts.
    Is there a way to get rid of "SELECT count(*) into PO_TOTAL FROM TABLE1;"?
    CREATE OR REPLACE PACKAGE BODY MYPACKAGE AS
    TYPE T_CURSOR IS REF CURSOR;
    PROCEDURE SP_PAGING
    PI_STARTID IN NUMBER,
    PI_ENDID IN NUMBER,
    PO_TOTAL OUT NUMBER,
    CUR_OUT OUT T_CURSOR
    IS
    BEGIN
    OPEN CUR_OUT FOR
    SELECT *
    FROM (SELECT row_.*, ROWNUM rownum_
    FROM (
    SELECT column1, column2, column3 FROM TABLE1
    ) row_
    WHERE ROWNUM <= PI_ENDID)
    WHERE rownum_ >= PI_STARTID;
    SELECT count(*) into PO_TOTAL FROM TABLE1;
    END SP_PAGING;
    END MYPACKAGE;

    Yes, I can reproduce that:
    SQL> create table emp1 as select * from emp
      2  /
    Table created.
    SQL> exec dbms_stats.gather_table_stats('SCOTT','EMP1');
    PL/SQL procedure successfully completed.
    SQL> EXPLAIN PLAN FOR
      2  SELECT  ename,
      3          job,
      4          sal,
      5          cnt
      6    FROM  (
      7           SELECT  ename,
      8                   job,
      9                   sal,
    10                   count(*) over() cnt,
    11                   row_number() over(order by 1) rn
    12             FROM  emp1
    13          )
    14    WHERE rn BETWEEN 4 AND 9;
    Explained.
    SQL> @?\rdbms\admin\utlxpls
    PLAN_TABLE_OUTPUT
    Plan hash value: 1444408506
    | Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |      |    14 |   728 |     4  (25)| 00:00:01 |
    |*  1 |  VIEW               |      |    14 |   728 |     4  (25)| 00:00:01 |
    |   2 |   WINDOW BUFFER     |      |    14 |   252 |     4  (25)| 00:00:01 |
    |   3 |    TABLE ACCESS FULL| EMP1 |    14 |   252 |     3   (0)| 00:00:01 |
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
       1 - filter("RN">=4 AND "RN"<=9)
    15 rows selected.
    SQL> EXPLAIN PLAN FOR
      2  SELECT *
      3  FROM (SELECT row_.*, ROWNUM rownum_
      4  FROM (
      5  SELECT ename,job,sal, count(*) over() FROM emp1
      6  ) row_
      7  WHERE ROWNUM <= 9)
      8  WHERE rownum_ >= 4;
    Explained.
    SQL> @?\rdbms\admin\utlxpls
    PLAN_TABLE_OUTPUT
    Plan hash value: 519025698
    | Id  | Operation             | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT      |      |     9 |   468 |     2   (0)| 00:00:01 |
    |*  1 |  VIEW                 |      |     9 |   468 |     2   (0)| 00:00:01 |
    |*  2 |   COUNT STOPKEY       |      |       |       |            |          |
    |   3 |    VIEW               |      |     9 |   351 |     2   (0)| 00:00:01 |
    |   4 |     WINDOW BUFFER     |      |     9 |   162 |     2   (0)| 00:00:01 |
    |   5 |      TABLE ACCESS FULL| EMP1 |     9 |   162 |     2   (0)| 00:00:01 |
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
       1 - filter("ROWNUM_">=4)
       2 - filter(ROWNUM<=9)
    18 rows selected.
    SQL> However, you interpreted it incorrectly. Your query will still fetch all rows in TABLE1. Optimizer is smart enough to stop creating window buffer after 9 rows and that is what you see 9 in explain plan, while my query builds 14 row window buffer and then filters. So your query will be a bit faster.
    SY.
    Edited by: Solomon Yakobson on Jan 25, 2009 2:51 PM

  • Getting the count of rows present in the oracle table

    Hi all,
    i want to get the total number of rows present in the sql table to the appmodule.
    After applying the some view criteria to the view object. if it try with getallrowsinrange it was giving count of rows present in the viewobject but i want total number of rows present in the sql table.
    How can i get that
    I am using jdev 11.1.1.5
    Thanks in advance

    I threw something together, quick and dirty, feel free to optimize.
    Assuming that you want the table count, I put the code into a EntityDefImpl subclass since this is what represents a table in the middle-tier.
    public class EmpDefImpl
          extends EntityDefImpl {
       * This is the default constructor (do not remove).
      public EmpDefImpl( ) {}
      //~ Methods ****************************************************************************
      public long getTableRowCount( DBTransaction transaction ) {
        String query = getQuery( );
        String countQuery = String.format( "SELECT COUNT(*) FROM (%s)", query );
        long count = 0;
        ViewObject vo = transaction.createViewObjectFromQueryStmt( countQuery );
        try {
          vo.executeQuery( );
          Row row = vo.first( );
          Number number = (Number)row.getAttribute( 0 );
          count = number.longValue( );
        } finally {
          vo.remove( );
        return count;
    }Depending on your type map, you might not get a oracle.jbo.domain.Number, but something else, so the cast might need correction.
    Usage example:
    public class EmpEditViewImpl extends ViewObjectImpl {
      public EmpEditViewImpl() {
      protected void executeQueryForCollection( Object object, Object[] object2, int i ) {
        super.executeQueryForCollection( object, object2, i );
        EmpDefImpl def = ( EmpDefImpl )getEntityDef( 0 );
        long tableRowCount = def.getTableRowCount( getDBTransaction() ) );
        // Do something with it
    }As you can see, the code is pretty generic. You might also be able to put this into an ADF extension base class.
    Sascha
    Edited by: Sascha Herrmann on Jun 7, 2012 2:39 PM

  • No Count all Rows in Discover Plus

    Hello,
    in Discoverer Desktop it is possible to count all rows (menue: sheet|Count all Rows) for a query. In Discoverer Plus Version 9.0.4 i am missing this feature. Is there a work around for this problem?
    Franz

    Thanks Marcus,
    i know, but it is a very slow way if you are selecting 10000 records. I don't understand why Oracle is not be able do add this feature like in the Desktop to Plus.
    Franz

  • 'Count all rows' in Disco Plus?

    Hi all - I can't find an option to Count All Rows in disco plus. This is something my users use all the time in Desktop - is it included in Plus?
    In Desktop, it is under menu item 'Sheet'
    Thanks!
    Scott

    Hi Scott
    Sorry that was removed from Discoverer Plus so you won't find a button for it. Having that there would force Discoverer to have to run the entire query just to give you the total count. Oracle considered this a waste of resource and query effort, which I sort of agree with because I can see what they are getting at, and so removed it.
    Best wishes
    Michael

  • Report.Services 2008 - get page-count or row-count in the c#-code

    hello
    is it possible to get from the ReportViewer-control / ServerReport the page-count or row-count after the
    reportViewerCheck.ServerReport.Refresh();
    statement ??
    many thanks in advance for any clue & regards
    Michael

    Hi Michael,
    Yes, you can get them. For row count, you can add a parameter to store the row count of your dataset in your report.
    Here are the steps:
    1.     Add 2 datasets in your report, one for report use and the other on is to row count use. For instance:
    DataSet1: SELECT     HumanResources.vEmployee.* FROM         HumanResources.vEmployee
    DataSet2: SELECT     COUNT(*) FROM         HumanResources.vEmployee
    2.     Add a parameter, set the parameter’s default value set to Get Values from a query and select DataSet2.
    Then, in your ASP.NET web application code you can use the following function to get the row count of the report:
    private int GetReportRowCount(ReportViewer report)
                return Convert.ToInt32(report.ServerReport.GetParameters()[0].Values[0].ToString());
    For page count, you can refer to the following code:
    private int GetReportPageCount(ReportViewer report)
                return report.ServerReport.GetTotalPages();
    You may not get the correct row count and page count in after executing Refresh () method, that’s because when you run this method, it will start another thread to refresh the report and the code below Refresh () method will not wait refreshing complete but run it. For instance, you may get the page count as o if you run the following code in the Button event:
    // Click this Button to refresh the ReportViewer1
            protected void btnGetPageCount_Click(object sender, EventArgs e)
                // Refresh the ReportViewer1
                this.ReportViewer1.ServerReport.Refresh();
                // Get ReportViewer1's page count and display in the txtPageCount TextBox
                this.txtPageCount.Text = this.ReportViewer1.ServerReport.GetTotalPages().ToString();
    You can run the refresh in separate events and get page count in another event, such as below code:
            // Click this Button to refresh the ReportViewer1
            protected void btnGetPageCount_Click(object sender, EventArgs e)
                // Refresh the ReportViewer1
                this.ReportViewer1.ServerReport.Refresh();
            // Display the txtPageCount's text to ReportViewer's page count
            protected void btnGetPageCount2_Click(object sender, EventArgs e)
                // Get ReportViewer1's page count and display in the txtPageCount TextBox
                this.txtPageCount.Text = this.ReportViewer1.ServerReport.GetTotalPages().ToString();
    Hope this helps! I would suggest you post a new thread in Visual Studio Report Controls forum if you need more help about using ReportViewer in ASP.NET web application.
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

  • Counting the rows

    Hi,
    I've a datamodel with BI Query. I want count the rows like a rownum function. How can I do this?
    Thanks R.
    Edited by: user12003776 on Jan 26, 2012 5:02 PM

    Do you want to get a count of rows in the query or do you want to find the count in the template? Rownum function returns the rows' position.
    If you want to find the count of rows within the template for some conditionally formatting, then you could use something similar to this:
    <?count(/XXTA_SHIP_LABEL/LIST_G_CUSTOMER/G_CUSTOMER)?> -- change the path to the field in your dataset
    Can you explain a bit more as to what you are trying to do?
    Thanks,
    Bipuser

  • 919: Column count replaces query count when opening table/view/etc tab

    I don't know whether this is intentional or not, but I have just noticed that opening a table or view tab from the connection pane replaces the existing query count message with the query count from the column query. For example, opening a table tab for a table with 14 columns sets the query count message to "All Rows Fetched: 14".
    This is not a big issue, but adds to the aggravation of only having the latest query count message, rather than one for each SQL Worksheet.
    Is it possible to find somewhere on the SQL Worksheet that we can put it's query count message (for example to the right of the execution time)?

    I am happy for querying the columns of a table/view/etc to display the fetch count of the columns, although I am rarely interested in how many columns there are in a table/view/etc.
    However, I already find it frustrating that the query count is only for the last fetch - it can be very useful having the query count for last fetch per SQL Worksheet. Having the last fetch overwritten by opening a table tab only makes it more frustrating.

  • Interactive Report  count selected rows

    I have a I/R report with a checkbox is column 1 of each row using:
    HTMLDB_ITEM.CHECKBOX
    (1,R.RESEARCH_ID,
    decode(:Pxx_SELECT_ALL_ROWS,'Y','CHECKED',
    decode(instr(nvl(:Pxx_SELECTED_IDS,0),R.RESEARCH_ID),0,NULL,'CHECKED'))
    AS select_flag
    I want to use Javscript or a Dynamic Action to "count" how many selected rows there are, when a UPDATE button is pressed.
    Right now, the UPDATE button "submits" the page, then a page item computation runs the following code to get a count:
    DECLARE
    v_cnt number(9);
    BEGIN
    v_cnt := 0;
    FOR i in 1..htmldb_application.g_f01.count
    LOOP
    v_cnt := v_cnt + 1;
    END LOOP;
    return v_cnt;
    This works... but I dont want to submit (and rerun the report) just to get this count.
    I have copied this loop into a Dynamic Action using the Click action of the UPDATE button, but it doesnt seem to recognize htmldb_application.g_f01.count .. so my value returns as 0.
    Any ideas - thanks!

    I am not that strong in javascript, so I put a few alerts in the function you provided, to try to understand it better.
    My example query returns 2 rows.
    document.wwv_flow.f01.length returns a value = 2.
    I checked both rows, then called the function.
    I put an Alert inside the FOR loop in your example, it never executed.
    The FOR loop in your example used a “>” sign, which never would evaluate as true, since i=0 > 2 is immediately false.
    I changed the operator in the FOR loop to “<”.
    The loop executed 2 times,
    I displayed the with variable i : values = 0, 1
    I displayed the value of document.wwv_flow.f01.id, it was NULL both iterations.
    The $x(curr_id).checked is never true, so count remains = 0
    function f_count_checked ()
    var counter = 0;
    for (var i = 0; i > document.wwv_flow.f01.length; i++) ---- I changed this to “<”
    {var curr_id = document.wwv_flow.f01[i].id;
    if ($x(curr_id).checked==true)
    {counter = counter + 1;}}
    alert ('You have checked: '+counter+' rows.');

  • Return Code - Query for Multiple Rows as XML

    Hi,
    I'm executing an MSSQL stored procedure through the "Query for Multiple Rows as XML" activity in LiveCycle ES. I do this through a call statement such as this:
    { call MyStoredProc(?) }
    This works great, the stored procedure always returns a record set (with or without records). I use this activity rather than "Call Stored Procedure" because I can transform the record set into XML right away within this activity. Unfortunately any exception arising from invoking this stored procedure cannot be handled within the workflow as this activity does not have an exception handler (lightning bolt). In an attempt to handle at least some exceptions we have decided to use try/catches within the stored procedures and return different error codes. Now the problem I am faced with is that there is no way to retrieve the returned code within any of the SQL activities. We don't want to have to write an execute script for each of these SQL calls. Is there any way to do this? Seems like I'm 95% there.
    Thanks
    Nic

    Thanks for the offer, unfortunately we would need something certified by Adobe.
    Nic

  • Count of rows from different tables.

    Hi Friends,
    I have 4 tables with a common column name "ID". I would like to get the count of rows from all the four tables which has the same ID.
    Ex
    select count(a.id) from table1 a,table2 b,table3 c,table4 d where a.id=b.id=c.id=d.id=5;
    please suggest me some solution

    may be thsi?
    select count(a.id) from table1 a,table2 b,table3 c,table4 d
    where a.id=b.id and a.id=c.id and a.id=d.id and a.id=5;

Maybe you are looking for

  • How to add 'Confidential' watermark to all the pages in portal

    Hi How to add 'Confidential' watermark to all the pages in portal.We have ESS/MSS business packages installed 60.1, 60.2. ECC5, EP SP16 is the environment. Help will be appreciated Thanks Sharath

  • Xml clause for group by statement t-sql.

    Hello , I have this data. create table #students id int identity(1,1) primary key, student_id int not null, [year] int not null, [subject] varchar(50) not null, [marks] int not null insert into #students student_id , [year] , [subject] , [marks] valu

  • Jms Protocol error

    Hi , I am using Oracle 10g version 10.1.3 and Oracle AS JMS Server I have a java client that is using the following configuration for JNDI conext. // set the environment properties env.put(Context.INITIAL_CONTEXT_FACTORY,"com.evermind.server.rmi.RMII

  • Problem : moving JComponent

    Hi, I try to write a program which allows to move subclasses of JRadioButton, JCheckBox and others JComponents. My problem is that the components seem to disappear like outside an invisibile window (I'm not sure if it's clear for u...). Here a bit of

  • Getting and error of Dynamic CRM Destination connection?

    Hi, I have used KingswaySoft Dynamic CRM Destination component to connect CRM 2013 in SSIS. bu getting below error when try to execute the package? [Dynamics CRM Destination [20]] Error: An error occurred with the following error message: "KingswaySo