Select count of sum

Hi
Need help with getting a count of different sums:
Table: Stay
Columns: Name, Nights
each name can have multiple rows with different number of nights, now I have a select looking like this:
select sum(nights),name from stay
group by name
The result could look something like this:
1 smith
2 miller
1 grant
1 simpson
2 sharp
How do I do to get a count on the sum(night)? Is it possible in the same query?

If you want to count how many distinct records appear in your current select statement (i.e. 5 in this case), you can do
SELECT count(*) num_distinct_guests,
       total_nights,
       name
FROM (
  SELECT sum(nights) total_nights,
         name
    FROM stay
  GROUP BY name
)If you want the total number of stays, in addition to the total time stayed, use something like
SELECT sum(nights),
       name,
       count(nights)
  FROM stay
  GROUP BY name;Justin

Similar Messages

  • Count vs sum(case) on dates in select statement

    I'm writing a statement to count the number of events occuring within 7 days of creating and also within 31 days of creating. I tried count but the script never completd. I've written this below - does anyone have a better idea on how to access the data? Thanks -
    select /*+ INDEX(CW_DOCUMENTS_IDX1) */ b.create_dt,
    sum(case when b.create_dt <= a.event_dt - 7 then 1 else 0 end),
    sum(case when b.create_dt <= a.event_dt - 31 then 1 else 0 end)
    from cw4_audit_index a, cw_documents b
    where a.docseq = b.docseq
    and a.medrecno = b.medrecno
    and a.account = b.account
    group by b.create_dt
    /

    Dianna,
    Just in case you’re still checking the thread … another explanation for the “never completed” symptom.
    Assuming a “cw_documents” row is created on “create_dt” and subsequently related “cw4_audit_index” event rows are created with a “event_dt” timestamp … then <quote>count[ing] the number of events occurring within 7 days of creating and also within 31 days of creating</quote> would be something like:
    case when cw4_audit_index.event_dt <= cw_documents.create_dt +  7 then 1 else 0 end
    case when cw4_audit_index.event_dt <= cw_documents.create_dt + 31 then 1 else 0 endor to use your own query:
    select /*+ INDEX(CW_DOCUMENTS_IDX1) */
           b.create_dt
          ,sum(case when a.event_dt <= b.create_dt +  7 then 1 else 0 end)
          ,sum(case when a.event_dt <= b.create_dt + 31 then 1 else 0 end)
    from   cw4_audit_index  a
          ,cw_documents     b
    where  a.docseq   = b.docseq
    and    a.medrecno = b.medrecno
    and    a.account  = b.account
    group by b.create_dt
    /With your version of the sql … didn’t you find cases of rows in your result set having more “within 7 days” events than “within 31 days”? … should’ve been a red flag right there.
    In my skimpy desktop, on a table with ~24K documents and ~1.44M events (some 60 events for each document, half of them within 31 days) I got the query in around 10 seconds … tables analyzed and no indexes in site … you’re probably fine here with nice/fat full table scans.
    Since an “within 7 days” event also/always qualifies as an “within 31 days” one … one could improve the above query by specifying an extra predicate:
    select b.create_dt
          ,sum(case when a.event_dt <= b.create_dt +  7 then 1 else 0 end)
          ,sum(case when a.event_dt <= b.create_dt + 31 then 1 else 0 end)
    from   cw4_audit_index  a
          ,cw_documents     b
    where  a.docseq   = b.docseq
    and    a.medrecno = b.medrecno
    and    a.account  = b.account
    and    a.event_dt <= b.create_dt + 31  --<< extra predicate
    group by b.create_dt
    /at which moment the second “sum” in the select list can be replaced with “count(*)” … the improvement percentage is based on your event distribution (how many events get filtered out up-front) … in my case, 10-25%.
    Cheers.

  • COUNT() and SUM() function it not working in XDO file.

    Hi ,
    I am getting one error. Count and sum function not working proper.
    For example :
    Department 10 have 3 employee and total salary is 8750. But my report returning total employee 1 and total salary 5000
    10
    Ename Sal
    KING 5000
    CLARK 2450
    MILLER 1300
    ==================
    total employee : 1
    total salary : 5000
    Kindly help me solve this problem.
    <dataTemplate name="TEXT">
    <properties>
    <property value="upper" name="xml_tag_case" />
    </properties>
    <lexicals>
    </lexicals>
    <dataQuery>
    <sqlstatement name="Q_TEMP">
    <![CDATA[SELECT DEPTNO,DNAME,LOC FROM DEPT]]>
    </sqlstatement>
    <sqlstatement name="Q_TEMP1">
    <![CDATA[SELECT ENAME,HIREDATE,SAL FROM EMP WHERE DEPTNO = :DEPTNO]]>
    </sqlstatement>
    </dataQuery>
    <datastructure>
    <GROUP name="G_1" source="Q_TEMP">
    <element value="DEPTNO" name="DEPTNO" />
    <element value="DNAME" name="DNAME" />
    <element value="LOC" name="LOC" />
    <GROUP name="G_2" source="Q_TEMP1">
    <element value="ENAME" name="ENAME" />
    <element value="SAL" name="SAL" />
    <element value="G_2.ENAME" name="TOTL_DETAILS" dataType="number" function="COUNT()" />
    <element value="G_2.SAL" name="TOTL_SAL" function="SUM()"/>
    </GROUP>
    </GROUP>
    </datastructure>
    </dataTemplate>
    Thanks
    Yudhi

    Please have the data structure as below:
    <datastructure>
    <GROUP name="G_1" source="Q_TEMP">
    <element value="DEPTNO" name="DEPTNO" />
    <element value="DNAME" name="DNAME" />
    <element value="LOC" name="LOC" />
    <GROUP name="G_2" source="Q_TEMP1">
    <element value="ENAME" name="ENAME" />
    <element value="SAL" name="SAL" />
    *</GROUP>*
    *<element value="G_2.ENAME" name="TOTL_DETAILS" dataType="number" function="COUNT()" />*
    *<element value="G_2.SAL" name="TOTL_SAL" function="SUM()"/>*
    *</GROUP>*
    </datastructure>
    Aggregate functions to be placed at the level you require it. Here you need at G_1, so place it there.

  • Any advice on count  when sum 0

    Hi there
    We would like to have 1 sql such that
    count when sum of value in column > 0 . Problem is sum an aggregate function and also count.
    As example imagine 2 customer records, one has a -ve value e.g -4 and 1 a positive value of +5 so sum of these values = +1. Such a customer we would like to include in the count and can't simply use having clause as we wish to include in report all sales reagrdless of whether > 0 but a separate count field to highlight the ones which are greater than 0
    Current sql
    select sum(value), cola..
    from table
    group by col1..
    can't say
    select count(case when sum(value) > 0 then distinct cust_id end)
    as get ora-message about nested group by functions..
    Anybody done such a thing before - would analytical functions work in this situation.
    Many Thanks

    Hi there,
    Thanks very much for the replies.
    One problem though, unfortunately the reporting tool we use is quite constrained and we can't implement the solutions proposed in it - they would have been preferable.
    Example of data
    table called transaction with all different types of transactions
    Main fields, trans-code, cust_id, product_id, trans_qty, trans_date
    Each row has a different trans code, e.g supply code, return code.
    We wish to identify no of custs sold out. A customer could have several supply transaction records for the same product and potentially several different return transactions.
    If the sum of all the supply transactions for a customer/product > 0 and the sum of all the credit transactions for a customer/product = 0 then we count this as a sell-out.
    Is it possible to code this as an analytical function - if so how?
    Many Thanks

  • Select count(*) and blank element tags

    Is there a way other than column aliases to produce and return an element tag for the following xsql query.
    <xsql:query
    connection="{@cxn}"
    xmlns:xsql="urn:oracle-xsql">
    select count(*) from emp
    </xsql:query>
    Some databases such as SQL Server via a JDBC driver will return a blank column name, thus you'll have an invalid XML document, however SQL Server allows one to use column aliases, such as select count(*) as "count" from emp.
    However some databases such as Progress via a JDBC-ODBC bridge and ODBC driver does NOT allow column aliases. Thus I'll always get the following response:
    <ERROR>oracle.xml.sql.OracleXMLSQLException: String index out of range: </ERROR>
    Question. Can I substitute an element tag when I encounter a blank column name using an action handler? Any ideas? Sample code?
    Steve.

    Please have the data structure as below:
    <datastructure>
    <GROUP name="G_1" source="Q_TEMP">
    <element value="DEPTNO" name="DEPTNO" />
    <element value="DNAME" name="DNAME" />
    <element value="LOC" name="LOC" />
    <GROUP name="G_2" source="Q_TEMP1">
    <element value="ENAME" name="ENAME" />
    <element value="SAL" name="SAL" />
    *</GROUP>*
    *<element value="G_2.ENAME" name="TOTL_DETAILS" dataType="number" function="COUNT()" />*
    *<element value="G_2.SAL" name="TOTL_SAL" function="SUM()"/>*
    *</GROUP>*
    </datastructure>
    Aggregate functions to be placed at the level you require it. Here you need at G_1, so place it there.

  • Help with count and sum query

    Hi I am using oracle 10g. Trying to aggregate duplicate count records. I have so far:
    SELECT 'ST' LEDGER,
    CASE
    WHEN c.Category = 'E' THEN 'Headcount Exempt'
    ELSE 'Headcount Non-Exempt'
    END
    ACCOUNTS,
    CASE WHEN a.COMPANY = 'ZEE' THEN 'OH' ELSE 'NA' END MARKET,
    'MARCH_12' AS PERIOD,
    COUNT (a.empl_id) head_count
    FROM essbase.employee_pubinfo a
    LEFT OUTER JOIN MMS_DIST_COPY b
    ON a.cost_ctr = TRIM (b.bu)
    INNER JOIN MMS_GL_PAY_GROUPS c
    ON a.pay_group = c.group_code
    WHERE a.employee_status IN ('A', 'L', 'P', 'S')
    AND FISCAL_YEAR = '2012'
    AND FISCAL_MONTH = 'MARCH'
    GROUP BY a.company,
    b.district,
    a.cost_ctr,
    c.category,
    a.fiscal_month,
    a.fiscal_year;
    which gives me same rows with different head_counts. I am trying to combine the same rows as a total (one record). Do I use a subquery?

    Hi,
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    user610131 wrote:
    ... which gives me same rows with different head_counts.If they have different head_counts, then the rows are not the same.
    I am trying to combine the same rows as a total (one record). Do I use a subquery?Maybe. It's more likely that you need a different GROUP BY clause, since the GROUP BY clause determines how many rows of output there will be. I'll be able to say more after you post the sample data, results, and explanation.
    You may want both a sub-query and a different GROUP BY clause. For example:
    WITH    got_group_by_columns     AS
         SELECT  a.empl_id
         ,     CASE
                        WHEN  c.category = 'E'
                  THEN  'Headcount Exempt'
                        ELSE  'Headcount Non-Exempt'
                END          AS accounts
         ,       CASE
                        WHEN a.company = 'ZEE'
                        THEN 'OH'
                        ELSE 'NA'
                END          AS market
         FROM              essbase.employee_pubinfo a
         LEFT OUTER JOIN  mms_dist_copy             b  ON   a.cost_ctr     = TRIM (b.bu)
         INNER JOIN       mms_gl_pay_groups        c  ON   a.pay_group      = c.group_code
         WHERE     a.employee_status     IN ('A', 'L', 'P', 'S')
         AND        fiscal_year           = '2012'
         AND        fiscal_month          = 'MARCH'
    SELECT    'ST'               AS ledger
    ,       accounts
    ,       market
    ,       'MARCH_12'          AS period
    ,       COUNT (empl_id)       AS head_count
    FROM       got_group_by_columns
    GROUP BY  accounts
    ,            market
    ;But that's just a wild guess.
    You said you wanted "Help with count and sum". I see the COUNT, but what do you want with SUM? No doubt this will be clearer after you post the sample data and results.
    Edited by: Frank Kulash on Apr 4, 2012 5:31 PM

  • Performance issue when using select count on large tables

    Hello Experts,
    I have a requirement where i need to get count of data  from a database table.Later on i need to display the count in ALV format.
    As per my requirement, I have to use this select count inside a nested loops.
    Below is the count snippet:
    LOOP at systems assigning <fs_sc_systems>.
    LOOP at date assigning <fs_sc_date>.
    SELECT COUNT( DISTINCT crmd_orderadm_i~header )
       FROM crmd_orderadm_i
       INNER JOIN bbp_pdigp
           ON crmd_orderadm_iclient EQ bbp_pdigpclient               "MANDT is referred as client
         AND crmd_orderadm_iguid  EQ bbp_pdigpguid
         INTO w_sc_count
    WHERE crmd_orderadm_i~created_at BETWEEN <fs_sc_date>-start_timestamp
         AND <fs_sc_date>-end_timestamp
         AND bbp_pdigp~zz_scsys   EQ <fs_sc_systems>-sys_name.
    endloop.
    endloop.
    In the above code snippet,
    <fs_sc_systems>-sys_name is having the system name,
    <fs_sc_date>-start_timestamp is having the start date of month
    and <fs_sc_date>-end_timestamp is the end date of month.
    Also the data in tables crmd_orderadm_i and bbp_pdigp is very large and it increases every day.
    Now,the above select query is taking a lot of time to give the count due to which i am facing performance issues.
    Can any one pls help me out to optimize this code.
    Thanks,
    Suman

    Hi Choudhary Suman ,
    Try this:
    SELECT crmd_orderadm_i~header
      INTO it_header                 " interna table
      FROM crmd_orderadm_i
    INNER JOIN bbp_pdigp
        ON crmd_orderadm_iclient EQ bbp_pdigpclient
       AND crmd_orderadm_iguid   EQ bbp_pdigpguid
       FOR ALL ENTRIES IN date
    WHERE crmd_orderadm_i~created_at BETWEEN date-start_timestamp
                                          AND date-end_timestamp
       AND bbp_pdigp~zz_scsys EQ date-sys_name.
        SORT it_header BY header.
        DELETE ADJACENT DUPLICATES FROM it_header
        COMPARING header.
        describe table it_header lines v_lines.
    Hope this information is help to you.
    Regards,
    José

  • "select count(*)" and "select single *" returns different result

    Good day!
    product version SAP ECC 6.0
    oracle10
    data transfers from external oracle db into customer tables using direct oracle db link
    sometimes I get case with different results from 2 statements
    *mytable has 10 rows
    *1st statement
    data: cnt type I value 0.
    select count( * ) into cnt from mytable WHERE myfield_0 = 123 and myfield_1 = '123'.
    *cnt returns 10 - correct
    *2nd statement
    select single * from  mytable WHERE myfield_0 = 123 and myfield_1 = '123'.
    *sy-dbcnt returns 0
    *sy-subrc returns 4 - incorrect, 10 rows are "invisible"
    but
    1. se16 shows correct row number
    2. I update just one row from "invisible" rows using se16 and 2nd statement returns correct result after that
    can not understand why
    thank you in advance.

    Thank you, Vishal
    but,
    general problem is that
    1. both statements have the same WHERE conditions
    2. 1st return resultset with data (sy-dbcnt=10), 2nd return empty dataset, but must return 1 in sy-dbcnt
    Yes, different meaning, you are right, but must 2nd must return 1, because of "select single *" construction, not 0.
    Dataset to process is the same, WHERE conditions are equal...
    I think the problem is that how ABAP interperets select count(*) and "select single *".
    Maybe "select count (*)" scans only PK from index page(s)? and "select single *" scans data pages? and something is wrong with that?
    I'm new in SAP and didn't find any SAP tool to trace dump of data and indexes pages with Native SQL.
    se16 shows all records.
    And why after simple manual update of just one record using se16 "select single *" returns 1?
    I've just marked one row to update, didn't change any data, then pressed "save".

  • Select count from large fact tables with bitmap indexes on them

    Hi..
    I have several large fact tables with bitmap indexes on them, and when I do a select count from these tables, I get a different result than when I do a select count, column one from the table, group by column one. I don't have any null values in these columns. Is there a patch or a one-off that can rectify this.
    Thx

    You may have corruption in the index if the queries ...
    Select /*+ full(t) */ count(*) from my_table t
    ... and ...
    Select /*+ index_combine(t my_index) */ count(*) from my_table t;
    ... give different results.
    Look at metalink for patches, and in the meantime drop-and-recreate the indexes or make them unusable then rebuild them.

  • Select count(*) statement in ABAP

    Hi,
    Im writing following statement in my Function module,
    select count(*) into l_count
    from user_master
    where username = l_username and
          process_type = processtype and
          password = oldpassword.
    And there is one entry in table user_master.
    But still, I'm getting l_count as zero..
    Can somebody help me with this.
    Regards,
    Amey

    select count(*) into l_count
    from user_master
    where username = l_username and
    process_type = processtype and
    password = oldpassword.
    Use group by option...
    Like this....
    select count(*) into l_count
    from user_master
    where username = l_username and
    process_type = processtype and
    password = oldpassword group by username.

  • Select Count(*) from Sample_table - how to get the count using JDBC?

    Hi All,
    It would be glad if anyone could help me with this. The problem is that I have to get the 'count' of records selected from a arbitrary table say, 'sample_table'. Is that possible to form the SQL in JDBC as
    Select Count(*) from Sample_table
    and get the value of the count? If yes, how?
    Thanks in advance
    Prabz

    stmt = con.createStatement();
    ResultSet recordcnt_rs = stmt.executeQuery("Select Count (*) as record_ctr From Sample_table");
    recordcnt_rs.next();     
    record_ctr = recordcnt_rs.getInt("record_ctr");
    hope this helps.

  • Select count(*) for each row of a table

    Hello All,
    Following query gives a statistics for each user (how many items he owns, home many tickets authored, how many objects he is subscribed to etc...)
    select auser.userid,
    (select count(*) from item where owner like '%' || auser.id || '%') ITEM_OWNER_CNT,
    (select count(*) from tkt where originator = auser.id) TKT_ORIGINATE_CNT,
    (select count(*) from tkt where assigned_to = auser.id) TKT_QA_CNT,
    (select count(*) from tkt where create_user = auser.id) TKT_AUTHOR_CNT,
    (select count(*) from subscriptions where subscriber_id = auser.id) SUBSCRIPTION_CNT
    from
    user auser
    I was not happy with the performance of this query, so I tried the same using group by. The performance was even worse.
    Is there any other option for me to try? Please advice.
    Thanks,
    Sathish

    Hi, Sathish,
    As SBH said, a lot depends on your data. Please post some sample data (CREATE TABLE adn INSERT statemetns) for all tables, and the results you want from that data. Describe and give examples of any relationships that are not one-to-one..
    You probably want to do joings, like SBH suggested, rather than scalar sub-queries.
    The connection between the auser and item tables
    (select count(*) from item where owner like '%' || auser.id || '%') ITEM_OWNER_CNT,is very suspicious. Perhaps the item table is poorly designed, and the query would be faster if that table were changed. Is changing the design of the item table an option?
    You should be able to get all the information from the tkt table in one pass. It looks like you need to unpivot the data, so instead of one row per ticket (with 3 different people connected to it), there are 3 rows per ticket, each with only 1 person referenced. This is not necessarily a bad table design. Unpivoting, even more than most other things, depends on your database version, so you'll have to tell what version of Oracle you're using.

  • Why is the select Count too slow

    I am doing the following select count and calling it from my JSP to get the total number of records... why is it so slow...
    select count(*)
    from
    (select distinct o.receive_id, o.name, o.address
    from order o, item i
    where o.id = i.id
    and o.status = 2 and i.status = 0)

    If the data in the table that you are referring to in the query gets refreshed very often and your high water mark on your table not reset, then this query always runs longer. While deleting data in the table, use 'TRUNCATE' rather than 'DELETE' in your data queries. that would help reset the high water mark and your count() queries will run very very fast.

  • Select count * is not working

    Hi everybody.
    I've got a very strange problem, when i'm doing a select count* the result is giving me a value that is not the maximum (but when i check the database table the maximum value is another..)
    Could it be that the select command is not executing against the table, rather than the SAP cache??
    If this is the case, how can i avoid this?? I mean force the select command to execute against de DB table.
    thanks a lot.

    to get max value of a table u can use
    Select max( fld )............
    Bypassing the SAP buffer with the above additions is a means to increase the performance when accessing buffered database tables. To explicitly bypass the SAP buffer in the SELECT statement, always use the addition BYPASSING BUFFER instead of the implicit behavior of the additions stated above.

  • Select Empno,name,sum()..group by empno only  Is this possible?

    select empno,name,sum(sal) from emptable where year=' ' groub by empno order by empno.
    this query getting error because i didn't include empname in group by.
    But if i include this name, my sum is not correct.
    so i want to empno,name but i don't want to include name in group by. Is this possible?
    My oracle verion is 8.
    IS any other solution to solve this problem?
    Thanks in advance.

    i want to empno,name but i don't want to include name in group by. Is this possible?<br>
    <br>
    No. It isn't.
    <br>
    select empno,name,sum(sal) over (partition by empno) <br>
    from emptable
    <br>where year=' '
    <br>
    -- <s>groub by empno</s>
    <br>
    order by empno;

Maybe you are looking for

  • Checking for outstanding commits in session ...

    (forms 9iR2, 9i DBMS) does anyone have any advice on if it is possible (and if so - how!) I can achive the following: I would like to find out if there is a requirement for carrying out a commit in my form, ie when an item on a block has changed, or

  • How to run a Unix Script from a specific user

    Hi, I want to run a GoldenGate related unix script from a super user. I have created crontab enter from that super user. But its still running from root user. As GGSCI cannot be invoked other than super user, the Script is failing. The Script is runn

  • What happen when an error occur when there are 2 threads running ?

    Here is my execution : My MainSequence calls another sequence in a new thread. This sequence call a VI continuously When an error occur in the MainSequence, nothing happen : The step with the error in Mainsequence is still in execution state (with th

  • Cannot boot Illustrator!

    Please help! Neither my Illustrator CS nor CS2 will boot up on my G5 PPC mac. No other Adobe product is affected nor is any other software program I run. The programs begin the startup process and for CS2 it simply never finishes, and for CS it crash

  • Upgrade to Firefox 11 and lost all bookmarks.

    I have upgrade to Firefox 11 and lost all bookmarks. None of the on-line articles help. Please advise on how to recover the bookmarks. I have tried to go to the pages that I use and it will not let me bookmark them. ''[Personal information removed by