Selecting a specific running total

I am trying to determine the GPA of the top 5 credits that student receives over a given set of terms.
My code...
CREATE TABLE #TEMP
COURSE_ID INT,
STUDENT INT,
TERM CHAR(2),
GRADE_PTS FLOAT,
CREDITS FLOAT
INSERT INTO #TEMP
(COURSE_ID, STUDENT,TERM,GRADE_PTS,CREDITS)
VALUES ('2436801','0441080','FA','86.00000','1.00000'),
('2379009','0441080','FA','82.00000','1.00000'),
('2379005','0441080','SU','41.50000','0.50000'),
('2487620','0441080','SU','41.00000','0.50000'),
('2487621','0441080','FA','40.50000','0.50000'),
('2483446','0441080','SU','40.00000','0.50000'),
('2458013','0441080','FA','40.00000','0.50000'),
('2379002','0441080','SU','40.00000','0.50000'),
('2379004','0441080','FA','39.00000','0.50000'),
('2379016','0551080','SU','38.00000','0.50000'),
('2458089','0551080','SU','37.00000','0.50000'),
('2379091','0551080','FA','86.00000','1.00000'),
('2379075','0551080','SU','43.00000','0.50000'),
('2379047','0551080','FA','76.00000','1.00000')
; with CTE as (
SELECT ROW_NUMBER() OVER(PARTITION BY STUDENT ORDER BY GRADE_PTS DESC) AS RN,
COURSE_ID, STUDENT, TERM,GRADE_PTS,CREDITS
FROM #TEMP A
WHERE TERM IN ('FA', 'SU') AND STUDENT = '0441080'
SELECT A.STUDENT,(SELECT SUM(B.GRADE_PTS) FROM CTE B WHERE B.RN<=A.RN)AS RT_GRADE_PTS,---RUNNING TOTAL FOR STC_CUM_CONTRIB_GRADE_PTS
(SELECT SUM(B.CREDITS) FROM CTE B WHERE B.RN<=A.RN) AS RT_CRED, ---RUNNING TOTAL FOR STC_CMPL_CRED
(SELECT SUM(B.GRADE_PTS) FROM CTE B WHERE B.RN<=A.RN)/(SELECT SUM(B.CREDITS) FROM CTE B WHERE B.RN<=A.RN) AS GPA ---CALCULATION FOR GPA
FROM CTE A
WHERE (SELECT SUM(B.CREDITS) FROM CTE B WHERE B.RN<=A.RN)=5
I would like the script to show 1 record for each STUDENT, GRADE_PTS (total), CREDITS (total) and GPA. The condition is that the calculatioins cannot be more than 5 total credits. Currently, I can only get the script to work for the first student based
on 5 credits but if there are less than 5 (3.5 in the case of student 551080) it should calculate the GPA on the top 3.5 credits.
Suggestions?

CREATE TABLE #TEMP
COURSE_ID INT,
STUDENT INT,
TERM CHAR(2),
GRADE_PTS FLOAT,
CREDITS FLOAT
INSERT INTO #TEMP
(COURSE_ID, STUDENT,TERM,GRADE_PTS,CREDITS)
VALUES ('2436801','0441080','FA','86.00000','1.00000'),
('2379009','0441080','FA','82.00000','1.00000'),
('2379005','0441080','SU','41.50000','0.50000'),
('2487620','0441080','SU','41.00000','0.50000'),
('2487621','0441080','FA','40.50000','0.50000'),
('2483446','0441080','SU','40.00000','0.50000'),
('2458013','0441080','FA','40.00000','0.50000'),
('2379002','0441080','SU','40.00000','0.50000'),
('2379004','0441080','FA','39.00000','0.50000'),
('2379016','0551080','SU','38.00000','0.50000'),
('2458089','0551080','SU','37.00000','0.50000'),
('2379091','0551080','FA','86.00000','1.00000'),
('2379075','0551080','SU','43.00000','0.50000'),
('2379047','0551080','FA','76.00000','1.00000')
--SQL Server 2012 or 2014
;with mycte as (
select *, sum(credits) Over(Partition by STUDENT Order by Grade_PTS DESC, COURSE_ID) runningTotal from #TEMP)
,mycte1 as (
Select * from mycte
WHERE runningTotal<=5
select STUDENT,SUM(GRADE_PTS) Grade_Pts , SUM(GRADE_PTS)/Max(runningTotal) GPA , Max(runningTotal) Credit from mycte1
GROUP BY STUDENT
--Prior SQL Server 2012
;with mycte as (
select STUDENT ,GRADE_PTS, credits, row_number() Over(Partition by STUDENT Order by Grade_PTS DESC, COURSE_ID) rn
from #TEMP
,mycte1 as (
SELECT a.STUDENT, GRADE_PTS, (SELECT SUM( credits) FROM mycte b WHERE b.rn <= a.rn and b.STUDENT=a.STUDENT) as runningTotal
FROM mycte a
Select STUDENT, SUM(GRADE_PTS) Grade_Pts , SUM(GRADE_PTS)/Max(runningTotal) GPA , Max(runningTotal) Credit from mycte1
WHERE runningTotal<=5
GROUP BY STUDENT
drop table #TEMP

Similar Messages

  • Running Total Variation Query Time Optimization

    Hi all, 
    I've been struggling with this query for a while. I need to set a customer specific running total for 10 million rows (reset for every customer). But every time the number goes negative, I need to set it as zero.
    For example,
    member no              amount            wallet
    member1                 400                      400
    member1                 -500                     0
    member1                  200                    200
    member2                  700                    700
    member2                 -200                    500
    Query:
    DECLARE @member float
    DECLARE @prev_member float
    DECLARE @amount float
    DECLARE @wallet float
    DECLARE db_cursor CURSOR FOR  
    SELECT [Member no], [Transaction Amount] 
    FROM [wallet_master_3]
    ORDER BY [Member No], [rownum]
    FOR UPDATE
    OPEN db_cursor
    FETCH NEXT FROM db_cursor INTO @member, @amount
    SET @prev_member = @member
    set @wallet=0
    WHILE @@FETCH_STATUS = 0
    BEGIN   
           IF @prev_member <> @member set @wallet=0
           SET @wallet = @wallet + @amount
           IF @wallet < 0 SET @wallet = 0
           UPDATE [wallet_master_3] SET walletsize = @wallet
           WHERE CURRENT OF db_cursor
           set @prev_member=@member
           FETCH NEXT FROM db_cursor INTO @member, @amount
    END   
    CLOSE db_cursor   
    DEALLOCATE db_cursor
    I've tried using a cursor. In five minutes, it ran 17,000 rows but after running it for 15 hours, the code only manages to set the running total for 175,000 rows. I'm not exactly sure why. Is there a faster approach I can use? 
    Thanks!

    As an exercise a 'Quirky Update' may help you in this scenario. Try the below trick!
    DECLARE @Wallet AS TABLE
    MemberNo VARCHAR(10),
    RowNum INT,
    Amount INT,
    Wallet INT
    INSERT INTO @Wallet (MemberNo, RowNum, Amount) VALUES
    ('member1',1, 400),
    ('member1',2, -500),
    ('member1',3, 200),
    ('member2',1, 700),
    ('member2',2, -200)
    DECLARE @RunTotal AS INT
    UPDATE W1
    SET
    @RunTotal = W1.Wallet =
    CASE
    WHEN W1.RowNum = 1 THEN W1.Amount
    WHEN @RunTotal + COALESCE(W1.Amount, W2.Amount) < 0 THEN 0
    ELSE @RunTotal + COALESCE(W1.Amount, W2.Amount)
    END
    FROM @Wallet W1
    LEFT OUTER JOIN @Wallet W2
    ON W1.MemberNo = W2.MemberNo AND W2.RowNum = W1.RowNum - 1;
    SELECT * FROM @Wallet;
    RESULT
    MemberNo RowNum Amount Wallet
    member1 1 400 400
    member1 2 -500 0
    member1 3 200 200
    member2 1 700 700
    member2 2 -200 500
    You can read more on 'Quirky Update' in below articles
    Solving the Running Total and Ordinal Rank Problems - Jeff Moden
    Robyn Page's SQL Server Cursor Workbench
    NOTE: Please test it thoroughly before using in a production environment!
    Krishnakumar S

  • How do I use a running total within a selection formula?

    I am developing a report within Crystal Reports 2008.  My goal is to identify any accounts that have zero usage for at least six months in this current year.  I have account number, meter size, read date, usage, and a running total/subtotal by account.
    Here is what the data looks like in the report
    ACCTNO     METER SIZE   READ DATE/TIME               READ_USAGE    Counter
    001022-05                    
    001022-05     2.00              9/28/2009  9:42:00 AM      0.00                     1
                                                                                    1
    001110-09               
    001110-09     2.00             3/2/2009  9:54:13 AM         0.00                      1
    001110-09     2.00             3/26/2009  1:32:28 PM        0.00                      1
    001110-09     2.00             4/27/2009  11:02:11 AM     0.00                      1
    001110-09     2.00             5/27/2009  1:13:53 PM        0.00                      1
    001110-09     2.00             6/19/2009  11:41:20 AM     0.00                      1
    001110-09     2.00     9/1/2009  8:13:25 AM         0.00                      1
                                                                                    6
    My report shows all accounts that have zero usage.  I want to filter the report to only show the accounts that have at least six zero usage reads.  I thought I could add a running total, sum it, and filter the data by using the selection formulas.  Unfortunately I keep getting an error message saying "this field cannot be used becuase it is being evaluated later."  Any help would be appreciated.  This is the first report I have created using crystal.
    Edited by: smwdrw2 on Oct 28, 2009 4:29 PM

    You could Conditionally suppress the account numbers where your running total is less than 6
    You will probably have to put your account number summaries in the group footer, instead of the header.
    Then:
    go to the section expert, click on the group footer for the account number, on the right, next to the word "Suppress" click on the box that says "X-2". In the formula put
    IF<6 then True
    Save and close
    The only way this would not work for you is if you have some sort of grand total that you don't want to include the other groups in.

  • Running total with specific criterea

    Hey Everyone,
    Quick question I hope. I have report that we want to add a running total of all records in the report that contain the numbers 1100 to 1400.
    What I have been trying to currently do is create running total sum that uses a formula to evaluate. But the result is that I seem to be totaling just about everything. Thanks very much for any insight tht you can offer.

    You'll have to excuse me as I'm not familiar with Basic syntax which is what I am assuming your posted formula is.
    It may not make much of a difference but perhaps try the formula in Crystal syntax?
    eg.
    {QryCrystalReports.CollCD} >= 1100 and {QryCrystalReports.CollCD} <= 1400
    Since you said you want this Running Total to check all records that the report pulled for the above-mentioned evaluation formula, I'd probably set the Reset option to "Never" if it has not been done already.

  • Running Totals Maybe?

    I am fairly new to Crystal Reports and Running Totals. I have a group setup that is based on the number of days a loan is late. For example, I have three buckets (30 Days, 60 Days, 90 Days). In setting up the group, I put the group in specific order and decided to exclude the other loans that are less than 30 days. I am trying to get a total $ amount of all the loans instead of just the loans in the buckets. I have searched forums and a Crystal 2008 book trying to figure this out. I tried using a Running Total with the Running Total expert but it is still giving me the same grand $ total that I have for the groups I selected. Any ideas? I am bit confused as to the multipassing of the data. Should I keep the groups setup the way I have them or use the select expert (etc).
    Thanks, I am a newbie.

    i suggest manual running totals, more accurate and if you have duplicate values the summary option will duplicate the data
    create 3 formuls
    i reset
    whileprintingrecords;
    numbervar x:= 0;
    this gets placed in the group header
    calculate
    whileprintingrecords;
    numbervar x:= x + field or formula;
    this gets placed next to the field or formula you want calculated
    display
    whileprinitngrecords;
    numbervar x;
    x
    this gets displayed in the footer of where the reset is (header)
    using manual running totals, if you have data on the report you dont want included you can create a formula that will only calc based upon only what should be included.

  • Oracle Reports : How to Create Filtered Running Totals

    I need to create a column in a group to represent a running total. But I want that running total to only count rows that meet specific criteria, such as [Field_Value_1] = 'Yes'. How can I accomplish this?

    make a hidden (hidden) column in select like decode(Field_value_1, 'Yes', Val_to_Sum, 0) and make running total on that column ...
    Hope This Helps

  • Showing  running totals on AR statatement Report

    Hi All I need assistance in populating the Running totals on AR statement Report  , I am trying to calculate the running total on the RDF using the (sum Over Partition ) and Not on the RTF template please assist .
    here is my query below :
    select customers.customer_name,
      detail.customer_id,
      detail.customer_site_use_id,
    :CP_ACC_NAME,
    :CP_ACC_NUM,
    :CP_BRNCH_NAME,
    :CP_COL_EMAIL,
    :CP_COL_PHONE,
    :CP_BRANCH_NR,
    decode(  (select meaning
    from ar_lookups
    where lookup_type = 'INV/CM/ADJ' and lookup_code =  detail.class), 'Payment', apply_date, trx.trx_date)  TRX_DATE,
    trx.INVOICE_CURRENCY_CODE,
    trx.INVOICE_CURRENCY_CODE INVOICE_CURRENCY_CODE_BAL,
    NVL(trx.term_due_date,trx.TRX_DATE)  term_due_date,
    detail.customer_id cst_id,
      detail.customer_site_use_id cst_site_id,
      detail.customer_trx_id,
      detail.trx_number,
       (select meaning
    from ar_lookups
    where lookup_type = 'INV/CM/ADJ' and lookup_code =  detail.class) class,
      detail.amount_full_original,
      detail.end_bal * -1 , (detail.end_bal + detail.amount_full_original)* -1  closing_balance ,
    detail.amount_full_original -  detail.the_order * -1  closing_bal,
      (detail.amount_full_original - detail.running_total) running_total ,
      detail.running_tot ,
      customers.customer_name address1,
      customers.address1 address2,
      customers.address2 address3,
      customers.address3 address4,
      customers.city||' '||customers.state address5,
      customers.country||' '||customers.postal_code address6,
      addr.address1 rm_address1,
      addr.address2 rm_address2,
      addr.address3 rm_address3,
      addr.address4 rm_address4,
      addr.address5 rm_address4,
       :p_as_of_date_from date_from,
       to_char(to_date(:p_as_of_date_to,'DD-MON-YYYY'),'DD-Mon-YYYY') date_to,
      addr.org_id rm_org_id,
       rtrim(to_char(sysdate,'DD')||' '||to_char(sysdate,'Month'))||' '||to_char(sysdate, 'YYYY') curr_date
    from (select customer_id, CUSTOMER_SITE_USE_ID, trx.CUSTOMER_TRX_ID,trx.TRX_NUMBER, null apply_date,ps.class,ps.AMOUNT_DUE_ORIGINAL amount_full_original, the_trx.end_bal,the_trx.running_total , the_trx.running_tot , 1 the_order
    select customer_trx_id, sum(acctd_end_bal) end_bal  , running_total  ,  running_tot
    SELECT ps.customer_trx_id ,
       sum(ar_calc_aging.begin_or_end_bal(ps.gl_date,ps.gl_date_closed,
       NULL,to_date(:p_as_of_date_from))
      * ps.amount_due_remaining) start_bal,
       sum(ar_calc_aging.begin_or_end_bal(ps.gl_date,ps.gl_date_closed,
       NULL,to_date(:p_as_of_date_to))
      * ps.amount_due_remaining) end_bal,
       sum(ar_calc_aging.begin_or_end_bal(ps.gl_date,ps.gl_date_closed,
       NULL,to_date(:p_as_of_date_from))
      * ps.acctd_amount_due_remaining) acctd_start_bal,
       sum(ar_calc_aging.begin_or_end_bal(ps.gl_date,ps.gl_date_closed,
       NULL,to_date(:p_as_of_date_to))
      * ps.acctd_amount_due_remaining) acctd_end_bal ,
       (sum(ar_calc_aging.begin_or_end_bal(ps.gl_date,ps.gl_date_closed,
       NULL,to_date(:p_as_of_date_from))
      * ps.amount_due_remaining) + sum(ar_calc_aging.begin_or_end_bal(ps.gl_date,ps.gl_date_closed,
       NULL,to_date(:p_as_of_date_to))
      * ps.acctd_amount_due_remaining) ) running_total ,  
       sum((sum(ar_calc_aging.begin_or_end_bal(ps.gl_date,ps.gl_date_closed,
       NULL,to_date(:p_as_of_date_from))
      * ps.amount_due_remaining) + sum(ar_calc_aging.begin_or_end_bal(ps.gl_date,ps.gl_date_closed,
       NULL,to_date(:p_as_of_date_to))
      * ps.acctd_amount_due_remaining) )) over (partition by ps.customer_trx_id  order by ps.customer_trx_id)running_tot
       FROM ar_payment_schedules_all ps
       WHERE ps.payment_schedule_id+0 > 0
       --JF2 AND ps.gl_date_closed >= to_date(:p_as_of_date_from)
       AND  ps.class IN ( 'CB', 'CM','DEP','DM','GUAR','INV')
       AND  ps.gl_date  <= to_date(:p_as_of_date_to)
       and org_id = nvl(:P_ORG_ID,org_id)--1246
       --and customer_id = :p_customer_id --1075
       --and CUSTOMER_SITE_USE_ID = :p_customer_site_id --1066
       --and customer_trx_id = 66291
       --'|| l_ps_org_where ||'
       GROUP BY ps.customer_trx_id ,ps.acctd_amount_due_remaining , ps.gl_date,ps.gl_date_closed ,ps.class , rownum 
      ps.customer_trx_id ,
       sum(ar_calc_aging.begin_or_end_bal(ps.gl_date,ps.gl_date_closed,
      ra.gl_date,to_date(:p_as_of_date_from))
      * ( ra.amount_applied  + NVL(ra.earned_discount_taken,0)
       + NVL(ra.unearned_discount_taken,0))) start_bal,
       sum(ar_calc_aging.begin_or_end_bal(ps.gl_date,ps.gl_date_closed,
      ra.gl_date,to_date(:p_as_of_date_to))
      * ( ra.amount_applied  + NVL(ra.earned_discount_taken,0)
       + NVL(ra.unearned_discount_taken

    Hi
    Yes i would like more help as i have never used group by roll up before
    SELECT p.employee_number,
    p.full_name employee_name,
    DECODE (p.sex, 'M', 'Male', 'F', 'Female') gender,
    (DECODE (p.per_information4,
    '01', 'Indian',
    '02', 'African',
    '03', 'Coloured',
    '04', 'White')) race,
    p.original_date_of_hire,
    a.effective_start_date startdate_current_position,
    RTRIM (SUBSTR (ps.NAME, 1, INSTR (ps.NAME, ';')), ';') current_position,
    ho.NAME current_organization,
    xx_return_company_name(a.person_id, a.effective_start_date) current_company,
    RTRIM (SUBSTR (ps1.NAME, 1, INSTR (ps1.NAME, ';')),';') previous_position,
    ho1.NAME previous_organization,
    xx_return_company_name(a1.person_id, a1.effective_start_date) previous_company,
    a1.effective_start_date startdate_prev_position
    FROM per_assignments_v2 a,
    per_assignments_v2 a1,
    per_all_people_f p,
    per_all_positions ps,
    per_all_positions ps1,
    hr_all_organization_units_tl ho,
    hr_all_organization_units_tl ho1
    WHERE a1.person_id = a.person_id
    AND NVL (a1.position_id, 9) <> a.position_id
    AND a1.effective_end_date = a.effective_start_date - 1
    AND p.person_id = a.person_id
    and ho.ORGANIZATION_ID=ps.ORGANIZATION_ID
    and ho1.ORGANIZATION_ID=a1.ORGANIZATION_ID
    AND a.effective_start_date BETWEEN p.effective_start_date AND p.effective_end_date
    AND a.position_id = ps.position_id
    and p.EMPLOYEE_NUMBER not in ('1','2','3')
    AND a1.position_id = ps1.position_id(+)
    order by p.full_name

  • Running total in report footer returning inaccurate result

    Post Author: smarkta
    CA Forum: Formula
    I am writing a report that contains 3 groups.  I have created running totals for each group that are accurate by selecting the group to evaluate and reset on.  now I need to basically sum the results of the all the group running totals but have had no success.  any tips on how to do this would be greatly appreciated.
    Thanks

    Post Author: Charliy
    CA Forum: Formula
    Were you doing a Distinct Count?  Did you have a formula on the Running Total?  What is there about the Group Totals that make them different than the final total.

  • How can I display the vendor associated with result of my running total sum

    I have a report that lists vendors with their most vecent order dates.  I need to set up a rotation so that the vendor with the latest order date is next to be selected.  I used the running total summary to pick the latest date.  How can I display the vendor associated with result of my running total summary?

    If your "latest" order date means the "oldest" order date, why don't you try this:
    Go to Report tab -> Record Sort Expert -> Choose your order date in ascending order
    This will make your oldest order your first record shown. 
    You can then create a running total count for each record.
    Lastly, in your section expert under conditional suppress X+2 formula, write this:
    {#CountRecords}>1
    The result will only show the oldest record in your report.
    I hope that helps,
    Zack H.

  • Running Total - How to summarize a formula field?

    I'm sorry if this comes over as stupid but I have got myself quite messed up and am not 100% au fait with Crystal Reporting.
    The aim of my report is to calculate the costs of selected tests and to calculate a grand total of all tests at the end.
    I have created a group of  jobtests.TestTypeName
    Details
    1. testTypeName - to show Test Name that is being calcutaed - Database field
    2. Count ({jobTests.testTypeName}, {jobTests.testTypeName}) - to show number of tests of that type - this is a formula field
    3. Analysis1 - to show the cost of that test type - Database field
    4. {@CountTests/TestType} * {jobTests.AnalysisN1} - to show the number of tests per test type mulitplied by the cost of that test type - this is a formula field
    Report footer
    Count ({jobTests.testTypeName}) - to count the total number of tests
    MY PROBLEM - I need to see the sum of 4, this would be my grand total
    Trying to run the Running Total I can't get it to Summarize the field 4 because it is a formula field.
    What can I do?
    Thanks.

    You can't do a SUM on a formula that uses another aggregate function.  However, for both 4 and your grand total, you just need to SUM() (with ",{jobTests.testTypeName}" for the #4 calc), as the database field will be the cost for each test in each record.
    HTH,
    Carl

  • Running total of calculated field in pivot

    VERSION: ORACLE 11
    TABLE:
    create table chart_detail (
    DIS        NUMBER,
    BLD_MO VARCHAR2(7),
    BLD        NUMBER(10),
    RPLC      NUMBER(10));DATA:
    insert into chart_detail values (60,'2011-03',0,2);
    insert into chart_detail values (150,'2011-04',10572,0);
    insert into chart_detail values (120,'2011-04',26449,5);
    insert into chart_detail values (30,'2011-04',0,1);
    insert into chart_detail values (60,'2011-04',0,7);
    insert into chart_detail values (90,'2011-04',0,9);
    insert into chart_detail values (120,'2011-05',5714,0);
    insert into chart_detail values (90,'2011-05',24557,1);
    insert into chart_detail values (60,'2011-05',0,4);
    insert into chart_detail values (30,'2011-05',0,0);
    COMMIT;EXPECTED RESULTS:
         2011-04                    2011-05               
    DIS     RPLC     BLD     TBLD     IPTV     RPLC     BLD     TBLD     IPTV
    30     1     0     37021     0.03     0     0     30271     0.00
    60     7     0     37021     0.22     4     0     30271     0.13
    90     9     0     37021     0.46     1     24557     30271     0.17
    120     5     26449     37021     0.59     0     5714     5714     0.17
    150     0     10572     10572     0.59               0     
    180               0                    0     
    TOTAL     22     37021               5     30271          PROBLEM: I need to have a running total of IPTV like in the above example. I can get the IPTV for each DIS/bld_mo but I don't know how to get the running total of it. In the script below I just used an example where I tried summing the IPTV like was done for build. I know it can't be done that way because IPTV is a calculated field in the query but if I substitute "APR_IPTV" with the formula for IPTV I get an error that window functions aren't allowed here. I do not know a way around this. I commented out the bad piece of code.
    PROBLEM SCRIPT:
    WITH  pivot_results  AS
      SELECT    dis
      ,    NVL (apr11_rep,  0)  AS apr11_rep
      ,    NVL (apr11_bld,   0)  AS apr11_bld
      ,    NVL ( SUM (apr11_bld)
                      OVER (ORDER BY dis DESC)
                    ,                 0
                    )        AS apr11_tbld
    ,      DECODE(NVL ( SUM (apr11_bld)
                      OVER (ORDER BY dis DESC)
                    ,                 0),0,0,ROUND(NVL(apr11_rep, 0)*1000/ NVL ( SUM (apr11_bld)
                      OVER (ORDER BY dis DESC)
                    ,                 0),2
                    ))        AS apr11_iptv               
    ,      NVL ( SUM (apr11_iptv)
                      OVER (ORDER BY dis DESC)
                    ,                 0
                    )        AS apr11_tiptv  
      ,    NVL (may11_rep,  0)  AS may11_rep
      ,    NVL (may11_bld,   0)  AS may11_bld
      ,    NVL ( SUM (may11_bld)
                      OVER (ORDER BY dis DESC)
                    ,                 0
                    )        AS may11_tbld
    ,      DECODE(NVL ( SUM (may11_bld)
                      OVER (ORDER BY dis DESC)
                    ,                 0),0,0,ROUND(NVL(may11_rep, 0)*1000/ NVL ( SUM (may11_bld)
                      OVER (ORDER BY dis DESC)
                    ,                 0),2
                    ))        AS may11_iptv
    ,      DECODE(NVL ( SUM (may11_bld)
                      OVER (ORDER BY dis DESC)
                    ,                 0),0,0,ROUND(NVL(may11_rep, 0)*1000/ NVL ( SUM (may11_bld)
                      OVER (ORDER BY dis DESC)
                    ,                 0),2
                    ))        AS may11_tiptv               
      FROM     chart_detail
      PIVOT     (  MAX (rplc)  AS rep
              ,  MAX (bld)  AS bld
              FOR  bld_mo   IN ( '2011-04'  AS apr11
                                             , '2011-05'  AS may11
    SELECT    CASE
            WHEN  GROUPING (dis) = 0
            THEN  TO_CHAR (dis)
            ELSE  'Total'
        END      AS dis
    ,    SUM (apr11_rep)  AS apr11_rep
    ,    SUM (apr11_bld)  AS apr11_bld
    ,    SUM (apr11_tbld) AS apr11_tbld
    ,    CASE
            WHEN  GROUPING (dis) = 0
            THEN  SUM (apr11_iptv)
        END      AS apr11_iptv
    ,    SUM (apr11_tiptv) AS apr11_tiptv
    ,    CASE
            WHEN  GROUPING (dis) = 0
            THEN  SUM (apr11_tpiptv)
        END      AS apr11_tiptv
    ,    SUM (may11_rep)  AS may11_rep
    ,    SUM (may11_bld)  AS may11_bld
    ,    SUM (may11_tbld) AS may11_tbld
    ,    CASE
            WHEN  GROUPING (dis) = 0
            THEN  SUM (may11_iptv)
        END      AS may11_iptv   
    FROM    pivot_results
    GROUP BY  ROLLUP (dis)
    ORDER BY  pivot_results.dis
    ;Thank you,

    Hi,
    So you know how to compute iptv for an individual row; the problem now is that you want to get a running total of iptv; is that it?
    The problem there is that computing iptv requires an analytic function, and analytic functions can't be nested. To get the results of nesting f (g (x)), where f and g are analytic funtions, you have to compute g in a sub-query, and then use the results as the argument to f in a super-query.
    Here's how to apply that to your situation:
    WITH  pivot_results  AS
         SELECT    dis
    -- April, 2011
           ,           NVL (apr11_rep,   0)  AS apr11_rep
           ,           NVL (apr11_bld,   0)  AS apr11_bld
           ,           NVL ( SUM (apr11_bld)
                                       OVER (ORDER BY dis DESC)
                          , 0
                          )               AS apr11_tbld
         ,      NVL ( 1000 * apr11_rep
                              / NULLIF ( SUM (apr11_bld) OVER (ORDER BY dis DESC)
                                          , 0
                   , 0
                   )               AS apr11_iptv
    -- May, 2011
           ,           NVL (may11_rep,   0)  AS may11_rep
           ,           NVL (may11_bld,   0)  AS may11_bld
           ,           NVL ( SUM (may11_bld)
                                       OVER (ORDER BY dis DESC)
                          , 0
                          )               AS may11_tbld
         ,      NVL ( 1000 * may11_rep
                              / NULLIF ( SUM (may11_bld) OVER (ORDER BY dis DESC)
                                          , 0
                   , 0
                   )               AS may11_iptv
           FROM     chart_detail
           PIVOT    (    MAX (rplc)  AS rep
                    ,    MAX (bld)   AS bld
                    FOR  bld_mo   IN ( '2011-04'  AS apr11
                                      , '2011-05'  AS may11
    SELECT    CASE
                  WHEN  GROUPING (dis) = 0
                  THEN  TO_CHAR (dis)
                  ELSE  'Total'
               END      AS dis
    -- April 2011
    ,           SUM (apr11_rep)  AS apr11_rep
    ,           SUM (apr11_bld)  AS apr11_bld
    ,           SUM (apr11_tbld) AS apr11_tbld
    ,           CASE
                  WHEN  GROUPING (dis) = 0
                  THEN  ROUND ( SUM (SUM (apr11_iptv))
                                          OVER (ORDER BY  dis)
                      , 2
               END      AS apr11_iptv
    -- May 2011
    ,           SUM (may11_rep)  AS may11_rep
    ,           SUM (may11_bld)  AS may11_bld
    ,           SUM (may11_tbld) AS may11_tbld
    ,           CASE
                  WHEN  GROUPING (dis) = 0
                  THEN  ROUND ( SUM (SUM (may11_iptv))
                                          OVER (ORDER BY  dis)
                      , 2
               END      AS may11_iptv
    FROM      pivot_results
    GROUP BY  ROLLUP (dis)
    ORDER BY  pivot_results.dis
    ;Output:
          APR11  APR11   APR11  APR11 MAY11  MAY11   MAY11  MAY11
    DIS    _REP   _BLD   _TBLD  _IPTV  _REP   _BLD   _TBLD  _IPTV
    30        1      0   37021    .03     0      0   30271    .00
    60        7      0   37021    .22     4      0   30271    .13
    90        9      0   37021    .46     1  24557   30271    .17
    120       5  26449   37021    .59     0   5714    5714    .17
    150       0  10572   10572    .59     0      0       0    .17
    Total    22  37021  158656            5  30271   96527As you can see, this is not quite what you wanted on the row where dis='150'. You asked for NULLS in the may11_rep, may11_bld and may11_iptv columns. You can get those results if you need them; just explain the rules that govern whether to display the values and when to display NULL.
    The way you posted the sample data and results, and the quantity of sample data were all excellent; it really helped me find a solution. Thanks.
    It would have also helped it you had explained how iptv is computed. Basically, iptv = 1000 * rep / tbld, right?
    It looks like most of this code:
    ,      DECODE(NVL ( SUM (may11_bld)
                      OVER (ORDER BY dis DESC)
                    ,                 0),0,0,ROUND(NVL(may11_rep, 0)*1000/ NVL ( SUM (may11_bld)
                      OVER (ORDER BY dis DESC)
                    ,                 0),2
                    ))        AS may11_iptvwas a way of avoiding divide by 0 errors; it would have been helpful if you had explained that.

  • Running total across 2 grouping

    Hi All
    I have created a crystal report and i have 2 remaining issues that i just cant get around.
    the report is basically about all the net stock position.
    the report is based on a query..that links sales order to all target documents that originate from the sales orders, i.e...deliveries, invoices, returns, credit notes.
    then i also brought in all the open purchase orders and the instock from the oitw
    i then sumed up the lines so the sales order > Delivery > invoice > credit note > returns all shows in one line..and if there is a different unit of measure it will be another line for that sales order
    the report is grouped:
                                  per warehouse
                                  per item
                                  per Sales Order Num
                                  per Item Unit of Measure
                                  per Line Num
    1st issue:
    in the selection criteria if the sales order is closed but if one of the delivery notes is open it should bring in the "whole set" not just the the open deliverys linked to the sales order.
    this is because the delivered quantities adds up to the net position of the stock.
    2nd issue:
    I have to work out a net postion
    formula: net stock = Oitw.instock + PO - remaining qty on sales order
    I got the sales order as a negative
    i used a running total formula, but it does not work if the sales order has more then one unit of measure.
    whileprintingrecords;
    If onfirstrecord or previous({Command.SO No.})<>{Command.SO No.} then
    numbervar remain_bal:= remain_bal + {@QTY}
    i tried to add another if statement..but does not work
    whileprintingrecords;
    If onfirstrecord or previous({Command.SO No.})<>{Command.SO No.} then
    If onfirstrecord or previous({Command.SO Uom)<>{Command.SO Uom.}  then
    numbervar remain_bal:= remain_bal + {@QTY}
    any help will be gladly welcomed..
    thank you all
    Jerusha

    Hi Dave
    Thank you very much for your feedback.
    I have been using the base UoM, ie InvQty field.
    my issues comes where i am grouping I am 1st grouping by sales order num, then by uom as the customer wants to see that as separate entries
    Example:
    SO Num     Uom     Qty     InvQty
    1               Bags     50         200
    1               Bulk     100        100
    This is the forumula for the running total:
    If onfirstrecord or previous ({Command.SO No.}) <> ({Command.SO No.}) then
    if ({Command.Doc Type}) = 'SO' then
        SO := SO + {@QTY}
    However when i "print" my total and add it to the footer.. it will show 200 instead of 300.
    Thanks
    Jerusha

  • Graphing a RUNNING TOTAL on a line graph

    So I'm having a lot of trouble putting my data on a chart. I have it all laid out here: files.me.com/redsteven1/glwk4v.numbers.zip
    Whenever I try to graph it though I run into a whole host of problems. Namely, that I can't get the values to plot on the chart at all.
    Not sure what the problem is... I select A2:G103... and I see the different series (for each Activity) show up in the legend, but nothing is plotted on the chart.
    I know that much of the table is blank... that's because I'll be adding to it every day.
    Ideally, the X-axis should be time/date.... May, June, July, and August can be the major tick marks. And the Y-axis would be number of hours spent on each activity.
    To further complicate things, the chart should really be a running total of time spent on each activity... so if I spend an hour on Activity 1 each day for 3 days... then on the third day I should have a plot of 3 hours... not 1.
    I know I didn't work things super well here... hopefully you can figure out what I mean by looking at the linked file : \
    Thanks in advance.

    I guess that line graph isn't the best one, I would use the Scatter one.
    You can't chart your datas as they are at this time.
    Every datas are date_time or duration values which can't be charted as is.
    Here, I converted the dates from column A into strings
    Then I added 6 columns in which I converted the durations into decimal hours.
    The original columns are hidden.
    The formula used to convert is a simple one.
    In H2, I inserted :     
    =STRIPDURATION(B)*24
    Fill to the right
    Fill Down
    to fill the other cells.
    Yvan KOENIG (VALLAURIS, France) dimanche 22 mai 2011 21:26:18
    Please :
    Search for questions similar to your own before submitting them to the community
    To be the AW6 successor, iWork MUST integrate a TRUE DB, not a list organizer !

  • Crystal reports - charting a variable to simulate a running total

    I have 2 sets of data as below :
    units
    costs
    What I am trying to do is generate a chart that for each month, reports the result of the formula
    sum of costs to date / sum of units to date
    Ideally, I would create 2 running totals
    RT costs
    RT units
    then a formula avg. cost to date = RT costs/ RT units
    and then for each month (x axis of the chart) plot avg/ cost to date
    BUT - crystal won't plot a data set based on running totals.
    So, I created a field with a psudo running total
    i.e.
    whileprintingrecords;
    numbervar unitsum;
    unitsum:=unitsum+units
    and similar for the costs.  Variable called costsum.
    Then a variable field
    whileprintingrecords;
    numbervar results;
    results:=costsum/unitsum
    So I though I could then plot the field with the variable results in it in the chart.  But no, I cannot see the field name in the data select list.
    Please advise how I can create my chart.
    Thanks
    Edited by: newbyr on Jul 7, 2010 12:20 PM

    With the best will in the world, I realise that charting does not like running totals,  What I am looking for is a workaround, or clever way of circumventing the problem.
    Before posting I did extensively search the forum and saw the link that DebiHerbert has suggested, and it is of no help at all.
    Thanks
    Edited by: newbyr on Jul 9, 2010 2:40 PM

  • How do I set a function = to *** in Numbers to have a running total

    Hi
    How can I set a function in numbers that is the same as "***" in excel.  I just want to have a column that accumulates the totals in another column.

    Select the cell where you want the results to appear, then type
              =Sum(
    Then hold down the Command key and click on each of the cells in the other column whose results/contents you want incorporated into the running total.
    Then type
    and press Return.

Maybe you are looking for

  • Probelm with Creating purchase order using BAPI_PO_CREATE1

    Hi Experts, I am trying to create a PO using the "BAPI_PO_CREATE1". The BAPI is returning a PO number but when I am checking for the same in ME23 its saying that the number doesnot exsists. In BAPI retrun I am gettig an info message as "Stock transpo

  • The picture with the email, The picture with the email

    This appears to be an easy question for which I can't find an answer. I have two email accounts and use Mail on OSX Mountain Lion. One account sends an identifying picture of me with each sent email and the other account sends a picture of my wife. 

  • Ipod resets when clicking the white button on click wheel

    I have a problem, everytime i go to MENU in order to select artist or album and i click the white button on the click wheel my ipod resets. It wont let me chose anything it only lets me shuffle see my pics and podcast but it wont let me get to the me

  • WebHelp Distribution - Best Practices

    Good Morning (or Afternoon as the case may be)! This question is less about Robohelp itself, but more about Documentation in general. Our CEO recently "came up with the idea" that we should begin hosting our application help on our website instead of

  • Messages don't delete

    I use Mac Mail with Snow Leopard and I have Cox as ISP provider.  I have set Mac mail preferences in my Macmail to delete messages from server after two weeks.  This never happens.  I have to go to Webmail and delete messages page after page.  i have