Tweaking a SUM query

Hello experts,
I'm working on Oracle 10g. My query needs to sample out accounts for whom, payment has been processed ( using "tracking_id" ).
Current Table structure with sample data:
Table BM -- around 7 million records
account_no | balance_due
12345 | 200
12345 | 100
12346 | 0
12346 | 99.0
Table BALANCE - 6.75 million records
account_no | tracking_id
12345 | 72422000
12345 | 72422010
12346 | 72422009
12346 | 72422020
I use the following Query to sample out the accounts for which payment has been processed along with their balances. The data is structured, such that, at any given time, the actual balance of the customer is the sum of all values in the " balance_due " field
create table paid29 as
select a1.account_no, sum(a2.balance_due) postpaid_balance
from BM a1, BALANCE a2
where a1.tracking_id between 72421000 and 72422050 and
a1.account_no = a2.account_no
group by a1.account_no; My query seems to work perfectly when the account_no's are distinct for a given payment cycle. However when there is more than one payment for a particular account ( there will be 2 tracking_id in this case for the same account) , my query seem's to be summing up the "balance_due" twice, instead of just summing up once before performing an insert. resulting in mis-match during reconciliation.
Any help to get around this problem will be very helpful. I've tried my best to be clear with my requirements. Please let me know if anymore info is required to help me fix the query.
Current Result:
Table paid29
account_no | balance_due
12345 | 600.0
12346 | 198.0
Expected Result:
Table paid29
account_no | balance_due
12345 | 300.0
12346 | 99.0
Regards,
novice.

You are running into Cartesian product.
Try something like:
SQL> With BALANCE as
  2  (
  3  SELECT 12345 account_no , 200 balance_due FROM Dual
  4  UNION ALL
  5  SELECT 12345 , 100 FROM Dual
  6  UNION ALL
  7  SELECT 12346 , 0 FROM Dual
  8  UNION ALL
  9  SELECT 12346 , 99.0 FROM Dual
10  ),
11  BM as
12  (
13  SELECT 12345 account_no, 72422000 tracking_id FROM Dual
14  UNION ALL
15  SELECT 12345 , 72422010 FROM Dual
16  UNION ALL
17  SELECT 12346 , 72422009 FROM Dual
18  UNION ALL
19  SELECT 12346 , 72422020 FROM Dual
20  )
21  -- end of test data
22  SELECT   a1.account_no, SUM (a2.balance_due) postpaid_balance
23      FROM (SELECT DISTINCT account_no
24                       FROM bm
25                      WHERE tracking_id BETWEEN 72421000 AND 72422050) a1,
26           balance a2
27     WHERE a1.account_no = a2.account_no
28  GROUP BY a1.account_no;
ACCOUNT_NO POSTPAID_BALANCE
     12346               99
     12345              300
2 rows selected.
SQL> Hope this helps.
Regards,
Jo

Similar Messages

  • Tweak for sql query - help needed for smalll change

    Hi.
    I am trying to run a script that checks for used space on all tablespaces and returns the results.
    So far so good:
    set lines 200 pages 2000
    col tablespace_name heading 'Tablespace' format a30 truncate
    col total_maxspace_mb heading 'MB|Max Size' format 9G999G999
    col total_allocspace_mb heading 'MB|Allocated' format 9G999G999
    col used_space_mb heading 'MB|Used' format 9G999G999D99
    col free_space_mb heading 'MB|Free Till Max' like used_space_mb
    col free_space_ext_mb heading 'MB|Free Till Ext' like used_space_mb
    col pct_used heading '%|Used' format 999D99
    col pct_free heading '%|Free' like pct_used
    break on report
    compute sum label 'Total Size:' of total_maxspace_mb total_allocspace_mb used_space_mb - free_space_mb (used_space_mb/total_maxspace_mb)*100 on report
    select
    alloc.tablespace_name,
    (alloc.total_allocspace_mb - free.free_space_mb) used_space_mb,
    free.free_space_mb free_space_ext_mb,
    ((alloc.total_allocspace_mb - free.free_space_mb)/alloc.total_maxspace_mb)*100 pct_used,
    ((free.free_space_mb+(alloc.total_maxspace_mb-alloc.total_allocspace_mb))/alloc.total_maxspace_mb)*100 pct_free
    FROM (SELECT tablespace_name,
    ROUND(SUM(CASE WHEN maxbytes = 0 THEN bytes ELSE maxbytes END)/1048576) total_maxspace_mb,
    ROUND(SUM(bytes)/1048576) total_allocspace_mb
    FROM dba_data_files
    WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
    GROUP BY tablespace_name) alloc,
    (SELECT tablespace_name,
    SUM(bytes)/1048576 free_space_mb
    FROM dba_free_space
    WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
    GROUP BY tablespace_name) free
    WHERE alloc.tablespace_name = free.tablespace_name (+)
    ORDER BY pct_used DESC
    The above returns something like this:
    MB MB % %
    Tablespace Used Free Till Ext Used Free
    APPS_TS_ARCHIVE 1,993.13 54.88 97.32 2.68
    APPS_TS_TX_IDX 14,756.13 1,086.88 91.37 8.63
    APPS_TS_TX_DATA 20,525.75 594.25 80.18 19.82
    APPS_TS_MEDIA 6,092.00 180.00 74.37 25.63
    APPS_TS_INTERFACE 13,177.63 366.38 71.49 28.51
    The above works fine, but I would like to further change the query so that only those tablespaces with free space less than 5% (or used space more than 95%) are returned.
    I have been working on this all morning and wanted to open it up to the masters!
    I have tried using WHERE pct_used > 95 but to no avail.
    Any advice would be appreciated.
    Many thanks.
    10.2.0.4
    Linux Red Hat 4.

    Thanks for that.
    What is confusing is that the below query works for every other (about 10 others) database but not this one (?)
    SQL> set lines 200 pages 2000
    SQL>
    SQL> col tablespace_name heading 'Tablespace' format a30 truncate
    SQL> col total_maxspace_mb heading 'MB|Max Size' format 9G999G999
    SQL> col total_allocspace_mb heading 'MB|Allocated' format 9G999G999
    SQL> col used_space_mb heading 'MB|Used' format 9G999G999D99
    SQL> col free_space_mb heading 'MB|Free Till Max' like used_space_mb
    SQL> col free_space_ext_mb heading 'MB|Free Till Ext' like used_space_mb
    SQL> col pct_used heading '%|Used' format 999D99
    SQL> col pct_free heading '%|Free' like pct_used
    SQL>
    SQL> break on report
    SQL> compute sum label 'Total Size:' of total_maxspace_mb total_allocspace_mb used_space_mb - free_space_mb (used_space_mb/total_maxspace_mb)*100 on report
    SQL>
    SQL> select /*+ALL_ROWS */
    2 alloc.tablespace_name,
    3 alloc.total_maxspace_mb,
    4 alloc.total_allocspace_mb,
    5 (alloc.total_allocspace_mb - free.free_space_mb) used_space_mb,
    6 free.free_space_mb+(alloc.total_maxspace_mb-alloc.total_allocspace_mb) free_space_mb,
    7 free.free_space_mb free_space_ext_mb,
    8 ((alloc.total_allocspace_mb - free.free_space_mb)/alloc.total_maxspace_mb)*100 pct_used,
    9 ((free.free_space_mb+(alloc.total_maxspace_mb-alloc.total_allocspace_mb))/alloc.total_maxspace_mb)*100 pct_free
    10 FROM (SELECT tablespace_name,
    11 ROUND(SUM(CASE WHEN maxbytes = 0 THEN bytes ELSE maxbytes END)/1048576) total_maxspace_mb,
    12 ROUND(SUM(bytes)/1048576) total_allocspace_mb
    13 FROM dba_data_files
    14 WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
    15 GROUP BY tablespace_name) alloc,
    16 (SELECT tablespace_name,
    17 SUM(bytes)/1048576 free_space_mb
    18 FROM dba_free_space
    19 WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
    20 GROUP BY tablespace_name) free
    21 WHERE alloc.tablespace_name = free.tablespace_name (+)
    22 ORDER BY pct_used DESC
    23 /
    ((alloc.total_allocspace_mb - free.free_space_mb)/alloc.total_maxspace_mb)*100 pct_used,
    ERROR at line 8:
    ORA-01476: divisor is equal to zero

  • Using a Sum query in Oracle Forms

    Greedings,
    I have the following query which works fine in PL/SQL but i cant get it working in Oracle forms as i get an error in SUM(SELECT...) . Any quidance on how i should fix my query to work in Forms?
    select
       Sum((SELECT kl.amount
                FROM S03_a_salfldg@oracle_to_sun kl
                WHERE Trim(kl.accnt_code)=Trim(a.acnt_code)
                AND kl.period between 2008001 AND 2008012 AND ROWNUM=1)) AS actual
       from so_budgets_cat a,a01_acnt@oracle_to_sun b,so_budgets_com c,so_budgets d
       where trim(a.acnt_code)=trim(b.acnt_code)
       AND a.cat=c.cat
       AND TRIM(d.acnt_code)=trim(a.acnt_code)
       AND d.business_object=10000103883
       AND d.business_object=c.bus_object
       AND d.business_object=a.business_object
       AND SubStr(d.period,1,4)=Trim(c.PERIOD_Y)
       AND C.period_Y BETWEEN substr(2008001,1,4) AND substr(2008001,1,4)
       GROUP BY a.cat,a.acnt_code,c.com,a.cat_desc,b.descr,d.acnt_code
       order by a.cat,a.acnt_code,c.com,a.cat_desc,b.descrThanks in advance

    And what error would that be? Also where are you using this query? In a from clause query? Also you didn't specify any version infos; as forms has it's own PL/SQL engine there is a possibility that you run in a version problem if the code runs fine in SQL*Plus but fails to compile in forms (e.g. when running Forms 6i against a 10g database). Without those informations answers to your question are based on guessings, and most likely will result in a question-answer ping-pong.
    cheers

  • Sum Query From 6 Tables

    I need to in SQL if possible sum the total from 6 different stores, who are all stored in a different database.  I would prefer not to use a make table (again if possible) would just like a direct query using maybe CTE?
    --Query 1
    Select sum(emp1Sales+emp2Sales+emp3Sales+man1Sales+man2Sales)
    From store1
    --Query 2
    Select sum(emp1Sales+emp2Sales+emp3Sales+man1Sales+man2Sales)
    From store2
    --Query 3
    Select sum(emp1Sales+emp2Sales+emp3Sales+man1Sales+man2Sales)
    From store3
    ...and so on.
    How can I Sum all of those sales in one query?  So instead of having 3 values returned have one query that returns all the values?

    Since its just a sum you can even do this
    Select Total1 + Total2 + Total3 AS Total
    FROM (
    Select sum(emp1Sales+emp2Sales+emp3Sales+man1Sales+man2Sales)
    As [Total1] From store1
    )t1
    CROSS JOIN
    Select sum(emp1Sales+emp2Sales+emp3Sales+man1Sales+man2Sales)
    As [Total2] From store2
    )t2
    CROSS JOIN
    Select sum(emp1Sales+emp2Sales+emp3Sales+man1Sales+man2Sales)
    As [Total3] From store3
    )t3
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • 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

  • Complex Multiple Table Sum Query

    Here's a doozy for you. It is a pretty large query (by my standards, anyway) that is pulling data from multiple tables to fill a GridView in ASP.NET. The query is independent of .NET, so I think this is the right place for this post.
    Summary: Trying to get all of the data from the main table and the children tables, in addition to summing up the matching values from two children tables.
    The main table is RA_INVOICES. Some of the children tables are RA_USERS, RA_STATUS, etc. The two tables I am having issues with are RA_SYSTEMINVOICES and RA_ADJUSTMENTINVOICES. The key is MAN_INVOICE_NUM. If there are no rows in either the System or Adjustment tables include MAN_INVOICE_NUM, I get nothing back from the query. Here is my current query (I removed any fields that are not joined in some way, except for the key):
    SELECT RA_INVOICES.MAN_INVOICE_NUM, RA_CURRENCIES.CURRENCY, RA_STATUS.STATUS, RA_REGIONS.REGION, RA_REASONS.REASON, RA_USERS.EMAIL AS EXPR5, RA_USERS_2.EMAIL AS EXPR4, RA_USERS_1.EMAIL, NVL(SUM(RA_SYSTEMINVOICES.SYS_INVOICE_AMT), 0) AS EXPR2, NVL(SUM(RA_ADJUSTMENTINVOICES.ADJ_INVOICE_AMT), 0) AS EXPR3
    FROM RA_INVOICES
    INNER JOIN RA_CURRENCIES ON RA_INVOICES.CURR_ID = RA_CURRENCIES.CURR_ID
    INNER JOIN RA_REASONS ON RA_INVOICES.REASON_ID = RA_REASONS.REASON_ID
    INNER JOIN RA_STATUS ON RA_INVOICES.STATUS_ID = RA_STATUS.STATUS_ID
    INNER JOIN RA_REGIONS ON RA_INVOICES.USER_GROUP_ID = A_REGIONS.REGION_ID
    INNER JOIN RA_USERS ON RA_INVOICES.CC_EMAIL_ID = RA_USERS.USER_ID
    INNER JOIN RA_USERS RA_USERS_1 ON RA_INVOICES.CCM_EMAIL_ID = RA_USERS_1.USER_ID
    INNER JOIN RA_USERS RA_USERS_2 ON RA_INVOICES.DCM_EMAIL_ID = RA_USERS_2.USER_ID
    INNER JOIN RA_SYSTEMINVOICES ON RA_INVOICES.MAN_INVOICE_NUM = RA_SYSTEMINVOICES.MAN_INVOICE_NUM
    INNER JOIN RA_ADJUSTMENTINVOICES ON RA_INVOICES.MAN_INVOICE_NUM = RA_ADJUSTMENTINVOICES.MAN_INVOICE_NUM
    GROUP BY RA_INVOICES.MAN_INVOICE_NUM, RA_CURRENCIES.CURRENCY,
    RA_STATUS.STATUS, RA_REGIONS.REGION, RA_REASONS.REASON, RA_USERS.EMAIL, RA_USERS_2.EMAIL, RA_USERS_1.EMAIL
    Optionally I need to add the following:
    HAVING (RA_INVOICES.MAN_INVOICE_NUM = 'xxxxxxxxxx')
    So... where there are values in both of the tables (System and Adjustment) for MAN_INVOICE_NUM, I get results. Otherwise, if there are no tuples exist in one or both of those tables for MAN_INVOICE_NUM, I get nothing at all.
    Sorry this is so complex. Thought I'd give you guys a good challenge. ;-)

    OK fellas (and ladies, if you happen to populate an Oracle board!)... one last question:
    The solution offered worked perfectly. I would like to see if I can accomplish one last thing with this query, and that is to do some inline math operation on the results of the query. Basically, I need to take RA_INVOICES.MAN_INVOICE_NUM and subtract SUM(NVL(RA_SYSTEMINVOICES.SYS_INVOICE_AMT, 0)) AS SYSTOTAL and SUM(NVL(RA_ADJUSTMENTINVOICES.ADJ_INVOICE_AMT, 0)) AS ADJTOTAL from it.
    I tried MAN_INVOICE_NUM - SYSTOTAL - ADJTOTAL AS TOTAL, but it returned "Error Message: ORA-00904: SYSTOTAL: invalid identifier."
    So I changed the math to say MAN_INVOICE_NUM - SUM(NVL(RA_SYSTEMINVOICES.SYS_INVOICE_AMT, 0)) - SUM(NVL(RA_ADJUSTMENTINVOICES.ADJ_INVOICE_AMT, 0)), but I am afraid of the performance implications this has... it already read the value, why should I make it do it all over again? This query will eventuall be pulling a BUNCH of rows... a year from now we'll be in the tens of thousands if the user does a global query (most of the time this query will have a WHERE statement limiting the results). Just trying to make this query as efficient as possible.
    The other alternative is to make this a SPROC. I'm clueless on SPROCS right now, but if I could gain a performance advantage using a SPROC, I'd rather do that.
    Thanks in advance for your help!

  • Simple sum query I need help with please

    I need a query to do something like this:
    select customer_site_use_id
    from ar_payment_schedules_all ps
    where ps.status = 'OP'
    AND NVL(ps.receipt_confirmed_flag,'Y') = 'Y'
    and exists (select (sum(ps1.acctd_amount_due_remaining) as amtdue)
    from ar_payment_schedules_all ps1
    where ps1.customer_site_use_id = ps.customer_site_use_id
    and amtdue < 0)
    and ps.customer_site_use_id = 1593
    I may be making this too difficult. I don't know if I need the exists clause and the second select statement. In the exists statement, if the sum of all of the acctd_amount_due_remaining in ar_payment_schedules_all for the same customer_site_use_id is less than 0, then it is in the results.

    Hi,
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Always say which version of Oracle you're using.
    I'm pretty sure you don't want an EXISTS sub-query. EXISTS returns TRUE if the sub-query finds any rows; it doesn't matter how many, or what's on them.
    Perhaps you want something like this:
    WITH     got_total_amount_due     AS
         SELECT       customer_site_use_id
         ,       SUM (acctd_amount_due)     AS total_amount_due
         FROM       ar_payment_schedules_all
         GROUP BY  customer_site_use_id
    SELECT    ps.customer_site_use_id
    FROM        ar_payment_schedules_all     ps
    JOIN       got_total_amount_due          td  ON  ps.customer_site_use_id  = td.customer_site_use_id
    WHERE       ps.status            = 'OP'
    AND       NVL ( ps.receipt_confirmed_flag
               , 'Y'
               )                 = 'Y'
    AND        ps.customer_site_use_id = 1593
    AND       td.total_amount_due       < 0
    ;That gives you access to the total amount for each customer_site_id

  • Sum query question

    Hey guys, sorry for a newbie question but here goes:
    I have a table with col1, col2, col3, col4
    where col1,col2 and col3 are values and col4 is the sum of the values.
    The problem is that the sum column is currently empty and I was wondering how do I write a query that will add the sum to each row?
    Thanks in advance for any help.

    Note that the posted solutions assume that col1, col2 and col3 are never null. If any of them could be null, then youe need to use NVL to avoid adding NULL to a number:
    SQL> SELECT a, b, c, a + b + c total
      2  FROM (SELECT 1 a, 2 b, 3 c FROM dual UNION ALL
      3       SELECT 1, 2, NULL FROM dual);
             A          B          C      TOTAL
             1          2          3          6
             1          2Also, why do you need to store the sum of columns in the sa,e row. You should just do the adding when you select the records. It would be simple enough to create a view over the base table that does that.
    John

  • Help in Total sum query

    Hello, How I can sum(code1). Every code1 has a group and every group's total (total_per) should be 100. I want to add the comments column in the result as well. Thanks.
    create table #Cumulate (code numeric (10), code1 numeric (10), total_per numeric(10),code_desc char(20))
    insert into #Cumulate values (1,121,10,'DHJ')
    insert into #Cumulate values (2,121,90,'DHJ')
    insert into #Cumulate values (3,121,10,'DHJ')
    insert into #Cumulate values (4,122,10,'CRT')
    insert into #Cumulate values (5,122,80,'CRT')
    insert into #Cumulate values (6,122,05,'CRT')
    insert into #Cumulate values (7,122,10,'CRT')
    insert into #Cumulate values (8,123,10,'DRT')
    insert into #Cumulate values (9,123,60,'DRT')
    insert into #Cumulate values (10,123,10,'DRT')
    insert into #Cumulate values (11,123,10,'DRT')
    insert into #Cumulate values (12,123,10,'DRT')
    insert into #Cumulate values (13,124,20,'DRT')
    insert into #Cumulate values (14,124,60,'DRT')
    insert into #Cumulate values (15,124,10,'DRT')
    insert into #Cumulate values (16,124,10,'DRT')
    insert into #Cumulate values (17,124,10,'DRT')
    --Results
    Code1 total_per Commments
    121   100         Total is 100
    122   105         Total is not 100
    123   100         Total is 100
    124   110        Total is not 100

    Try the below:
    Select Code1, Sum(Total_per) total_per, 'Total is '+Case when Sum(Total_per)=100 then '' else ' not' end+'100' Comments
    From
    #Cumulate
    Group by Code1
    However, I would suggest you to do the comment session at presentation layer, which would be a good for performance.
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped.
     [Blog]

  • SQL query SUM and AVG

    Hi all,
    I think I'm being really stupid but I'm having SQL query issues.
    I have a table with lots of lines of transactions which all refer to different stores, for example:
    Store..............._Sales_............._Month_
    Reading............200k..............April
    Leeds...............50k................April
    Manchester........70k................May
    Reading............100k..............May
    I need to come up with the average Sales for the combined months as a total. I.e. the average Store revenue for a given period is 200k+ 50k + 70k +100k / *3* (As there are only 3 unique stores) - hopefully this makes sense!
    So essentially I am trying to do both a SUM query (and grouping by store) and then outputting the average of all stores together. Is this possible?
    Thank you,

    Hello,
    This query returns 140 what seems to be the correct value:
    with data as
    ( select 'Reading' Store
      , 200 sales
      from dual
      union
      select 'Leeds'
      , 50
      from dual
      union
      select 'Manchester'
      , 70
      from dual
      union
      select 'Reading'
      , 100
      from dual
    select sum(sales)
    , count( distinct store )
    , sum(sales)/count(distinct store)
    from dataThere are multiple options:
    1. You can get two IR's on one page (by using IFRAMEs - search for that word on the Forum)....
    2. You create another region with the query above and position that just below the report
    3. In the Region Footer call a PL/SQL process (using AJAX) that calculates the value using the query and prints it there (using htp.p)
    Greetings,
    Roel
    http://roelhartman.blogspot.com/
    http://www.bloggingaboutoracle.org/
    http://www.logica.com/
    You can award this reply to your question by marking it as either Helpful or Correct ;-)

  • Unable to setup fixed number of report columns based on a dynamic query

    Hi guys, I need to find a way to replicate below output. Unfortunately it cannot be done using the column group feature due the fact it will create not so many rows as I need. In the below case it would create
    only four columns. I need 10 columns. Basically for 100 m 6 columns would remain blank . 8 for 200 m .I'm using SRSS 2008R2
    Query results:
    Race Name Ranking
    100m Andrew 1
    100m Rachel 2
    100m Chris  3
    100m  Drew 4
    200m John 1
    200m  Billy 2
    Report output should look like:
    Race    1 2    3 4 5 6 7 8 9  10
    100m  Andrew Rachel Chris Drew
    200m John Billy
    Any suggestions?

    As I understand, you want a fixed number (10) of columns and you want them whether or not there are 10 rows returned by your dataset for a given race.
    What is your dataset?
    What if your dataset returns 15 races of a given type? Do you want 15 columns then?
    Assuming your dataset is TSQL, you can use a matrix in your report if you tweak your dataset query. First, you need to add a "default" set of data that guarantees your 10 columns. This can be done with a set of UNION statements:
    UNION
    SELECT '100m' AS Race, '' AS Name, 1 AS Ranking
    UNION
    SELECT '100m' AS Race, '' AS Name, 2 AS Ranking
    UNION
    SELECT '100m' AS Race, '' AS Name, 3 AS Ranking
    UNION
    SELECT '100m' AS Race, '' AS Name, 4 AS Ranking
    UNION
    SELECT '100m' AS Race, '' AS Name, 5 AS Ranking
    UNION
    SELECT '100m' AS Race, '' AS Name, 6 AS Ranking
    UNION
    SELECT '100m' AS Race, '' AS Name, 7 AS Ranking
    UNION
    SELECT '100m' AS Race, '' AS Name, 8 AS Ranking
    UNION
    SELECT '100m' AS Race, '' AS Name, 9 AS Ranking
    UNION
    SELECT '100m' AS Race, '' AS Name, 10 AS Ranking
    This gives you the 10 columns. In the matrix, set row group to Race and column group to Ranking. Set the intersecting detail cell to:
    =Max(Fields!Name.Value)
    This will give you 10 columns unless you have more than 10 rows returned for a given race.
    "You will find a fortune, though it will not be the one you seek." -
    Blind Seer, O Brother Where Art Thou
    Please Mark posts as answers or helpful so that others may find the fortune they seek.

  • Submit query button

    I am working in oracle 10g with developer 2000 as front end (forms and reports 9i) which was developed by software professional. unfortunately i don't have any source code or user manual of the project done by them.
    I have a small problem for which i need help / guidance to solve it.
    There are around 300 reports in the package and in all the reports the submit query and reset button is placed on the top of the page . It makes me uncomfortable to go to the top of the page after entering all the parameters for the report.
    I did check from the source of that page and i found out where the submit query and reset button is and placed it at the bottom as per my requirement. But i don't know where the changed source should be saved. since if i run from the changed htm file the sumit query button is at the bottom, but if i run the report from the front end it is at the top without the changes.
    i would be thankful if i could get some suggestion as to where this htm file will be in the package and how to make the changes.
    thanks in advance

    HTML-pages are not really related to forms. anyway, if they are static html-files, i would look somewhere on the application-server. But they may also be creeated by a servlet or contained in a deployment on the application-server.

  • Query Estimated Completion Time

    Hello ,
       Good Morning. I recently started supporting new set of databases from different team and I am having the problem of
    figuring out how much time Stored procedure is going to take to complete?
    Some of the queries take few hours and I am pretty much left in the dark and I don't have historical knowledge of those stored procedures.
    I am trying to figure out is there any options available to figure out the estimated completion time for a given query or operation?.
    How does other folks solve this problem?
    sys.dm_exec_requests DMV's estimated completion time is 0. 
    I understand the time to complete a query depends on numerous factors ( CPUS, other running processes, Preemptive/non preemptive mode, blocking, page reads, writes, etc ,etc ).
    I am really interested in knowing how other people handle this problem because its new set of databases for me.
    Appreciate your help.
    Cheers,
    I90Runner
    I90Runner

    Taken from Glenn Berry's excellent SQL Server Diagnostic Queries:
    -- Top Cached SPs By Avg Elapsed Time
    SELECT TOP(25) p.name AS [SP Name], qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
    qs.total_elapsed_time, qs.execution_count, ISNULL(qs.execution_count/DATEDIFF(Second, qs.cached_time,
    GETDATE()), 0) AS [Calls/Second], qs.total_worker_time/qs.execution_count AS [AvgWorkerTime],
    qs.total_worker_time AS [TotalWorkerTime], qs.cached_time
    FROM sys.procedures AS p WITH (NOLOCK)
    INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
    ON p.[object_id] = qs.[object_id]
    WHERE qs.database_id = DB_ID()
    ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
    This will give you an indicator of just how slow, the slowest Stored Procedures are in the Plan Cache.
    You can easily tweak the above query to look at all historically executed SPs or filter for just those that you are interested in looking at.
    Of course this is all retrospective information. The only way to know for sure how long a given stored procedure is going to take to run, is to run it.
    John Sansom | SQL Server MCM
    Blog |
    Twitter | LinkedIn |
    SQL Consulting

  • Trouble trying to replicate GROUP BY/DISTINCT and SUM in PowerPivot with DAX

    I have the following records table (ignore the commas)
    unqPath, Channel, PathLength, UnqPathLength
    8726, direct, 2, 2
    8726, direct, 2, NULL
    8726, organic, 1, 1
    28364, paid, 2, 2
    28364, display, 2, NULL
    287364, email, 4, 4
    287364, email, 4, NULL
    287364, direct, 4, NULL
    287364, email, 4, NULL
    Each record (unqPath) can have multiple channels. For each record I have Path length which is the number of channels associated with that record (this was achieved in SQL doing a count and partitioning it over record name). I have also created another column
    called UnqPathLength where I list the PathLength for each record only once (on the row associated with the 1st channel)
    In PowerPivot, I want to sum the PathLength of all records where a certain channel appears. So direct appears in 2 records which have Path Lengths 2 and 4 respectively so I'd like to have 6 for that.
    I have tried everything from using summarise, distinct but the path length is almost always double counted when the same channel appears twice in the same record. Also tried using unqPathLength (figured this would help with the duplicate counting) but it
    only works when the channel is on the same row and returns incorrect results.
    Here are some of my efforts
    # pathLengthChannel:=
    SUMX(
    SUMMARIZE(
    'query',
    'query'[unqPath],
    'query'[channel],
    'query'[pathLength],
    "pathLengthChannel0",
    SUM('query'[pathLength])
    ),[pathLengthChannel0]
    )OR# pathLengthChannel:=SUMX(
        DISTINCT([unqPath]),
        SUM('query'[pathLength])
    Any ideas would be greatly appreciated. Many thanks.

    This should work assuming that whenever the unqPath and channel are the same that the pathLength is too:
    =SUMX(
    SUMMARIZE(
    query,
    query[unqPath],
    query[Channel],
    "Path",
    MAX(query[PathLength])
    [Path]

  • Sum formula doesn't change when add row

    This question is about Numbers.  I have a column of numbers with a sum cell at the bottom of the column.  Sometimes I need to insert a row at the very bottom of the column, just above the cell with the Sum formula.  I then need to tweak the sum formula to include that added row; however, if I add a row in the middle of the column, the sum formula automatically changes to include that added row. 

    Hi c,
    Numbers will automatically adjust the formula if all body cells above the added cell have the same formula, or if the added cell is within the range specified in the formula.
    In the middle of the column, the second is true. At the end of the column, the added cell is outside the range specifired in your formula, and there is at least one regular cell above that does not contain the same formula.
    Use one or more header rows at the top of the table for your labels. Use a Footer row to hold the SUM formula. Place the SUM formula in the Footer row, using =SUM(B) for example to SUM the values in all of the body cells in column B.
    Regards,
    Barry

Maybe you are looking for

  • Problem migrating ear from Oracle AS 10g to 11g.

    Hi I need to deploy an ear file in Oracle AS 11g. The ear has war in it. The ear file has uix pages and the supporting files (EOs and VOs). Using Oracle AS 10g: Here, i used to create a OC4J container and deploy the ear in this container. Using Oracl

  • Use HP network printer in OS 9.2.2 without official driver?

    Hello! I have a HP Photosmart C5180 All-in-one which is connected over ethernet to a router. I also have an old PowerMac G4 (and an iMac G3) that boot into OS 9 and 10.3 and/or 10.4. While I usually use the G4 under Tiger, I'll often boot into OS 9 t

  • No picture on tv from 160GB classic

    having read all the forums re the problems with the TV OUT function on the new 160GB classic i find that i have no problem with that ....but i can get no picture on tv from connecting using the apple AV cable to the AV input on a new panasonic TV. i

  • Import dumpfile with seperate tablespaces for table and index

    Hi, We have a schema for which the its tables are stored in seperate tablespace and indexes are stored in different tablespace. Now we have take full schema export. Now we want to import it on another schema. Now I want to know if the we have differe

  • Durable Subscription with MDB in Weblogic 7.0

    Hi,           I am using WLS 7.0 as the JMS Provider and as the EJB Container(no           clustering). My question is do I need MDB with durable subscription. I           cannot think of a instance when the container will be down but JMS           p