Running total for duplicate rows
Hi,
I am trying to write an sql which shows the running total for records which has duplicate. Please share any idea to get this.
sample rows:
col1 col2 col3
1 A 2
1 A 2
1 A 2
1 B 3
1 B 3
1 C 5
1 D 2
1 D 2o/p required:
col1 col2 col3 cumulative_tot
1 A 2 2
1 A 2 2
1 A 2 2
1 B 3 5
1 B 3 5
1 C 5 10
1 D 2 12
1 D 2 12
Hi,
Try this:
WITH A AS
select 1 col1, 'A' col2, 2 col3 from dual union all
select 1 col1, 'A' col2, 2 col3 from dual union all
select 1 col1, 'A' col2, 2 col3 from dual union all
select 1 col1, 'B' col2, 3 col3 from dual union all
select 1 col1, 'B' col2, 3 col3 from dual union all
select 1 col1, 'C' col2, 5 col3 from dual union all
select 1 col1, 'D' col2, 2 col3 from dual union all
select 1 col1, 'D' col2, 2 col3 from dual
,B AS
SELECT
A.*
,ROW_NUMBER() OVER (PARTITION BY COL1, COL2 ORDER BY 1) RN
FROM
A
SELECT
B.*
,SUM(CASE WHEN RN = 1 THEN COL3 ELSE 0 END) OVER ( ORDER BY COL1, COL2 ,RN ) cumulative_tot
FROM
B
COL1 COL2 COL3 RN CUMULATIVE_TOT
1 A 2 1 2
1 A 2 2 2
1 A 2 3 2
1 B 3 1 5
1 B 3 2 5
1 C 5 1 10
1 D 2 1 12
1 D 2 2 12
8 rows selected Regards,
Peter
Similar Messages
-
Running Total for "cleared balance"
I want to produce query that will produce two running totals. The 1st once is straight forward and is 'Ledger Balance' - that is the balance after a particular transaction has taken place on that day. The Cleared Balance is the running total balance accounting for the value date of a transaction. For example a transaction for today, say $50 may be value dated tomorrow and hence is included in the Ledger Balance but would not appear in the Cleared balance until tomorrow.
Lets try and use some simple data:
TransactionsTable
Tran_ID TranDate ValueDate Amount
1 01/02/2004 01/02/2004 50
2 01/02/2004 01/02/2004 25
3 01/02/2004 05/02/2004 30
4 01/02/2004 01/02/2004 55
5 02/02/2004 04/02/2004 11
6 02/02/2004 02/02/2004 23
7 02/02/2004 02/02/2004 33
8 02/02/2004 02/02/2004 47
9 04/02/2004 04/02/2004 10
10 07/02/2004 07/02/2004 5
StatementHistory
AC_No Start_Date End_Date Opening_Ledger Opening_Cleared
55 02/02/2004 02/02/2004 160 130
55 04/03/2004 04/02/2004 274 233
Assuming that the account opened on the 01/02/04 with a zero balance.
So for a daily statement on the 01/02/04, I'd expect to see the following Details
TranDate ValueDate Amount Ledger Balance Cleared Balance
01/02/2004 01/02/2004 50 50 50
01/02/2004 01/02/2004 25 75 75
01/02/2004 05/02/2004 30 105 75
01/02/2004 01/02/2004 55 160 130
So for a daily statement on the 02/02/04, I'd expect to see the following Details
TranDate ValueDate Amount Ledger Balance Cleared Balance
02/02/2004 04/02/2004 11 171 130
02/02/2004 02/02/2004 23 194 153
02/02/2004 02/02/2004 33 227 186
02/02/2004 02/02/2004 47 274 233
And skipping to the 04/02/04, I'd expect to see.
04/02/2004 04/02/2004 10 284 254
I can get the ledger balance using:
sum(amount_to_account) OVER (PARTITION BY ac_no , trans_ID
ORDER BY TranDate, trans_ID
RANGE UNBOUNDED PRECEDING)
+ sh.Opening_Ledger
But I'm unsure how to get the Cleared balance as this need to access transaction inforation from a number of days previous (possibly up to 5 days allowing for maximum period for clearing a transaction).
Does anyone have an idea how to achive this?Hi,
Try this:
WITH A AS
select 1 col1, 'A' col2, 2 col3 from dual union all
select 1 col1, 'A' col2, 2 col3 from dual union all
select 1 col1, 'A' col2, 2 col3 from dual union all
select 1 col1, 'B' col2, 3 col3 from dual union all
select 1 col1, 'B' col2, 3 col3 from dual union all
select 1 col1, 'C' col2, 5 col3 from dual union all
select 1 col1, 'D' col2, 2 col3 from dual union all
select 1 col1, 'D' col2, 2 col3 from dual
,B AS
SELECT
A.*
,ROW_NUMBER() OVER (PARTITION BY COL1, COL2 ORDER BY 1) RN
FROM
A
SELECT
B.*
,SUM(CASE WHEN RN = 1 THEN COL3 ELSE 0 END) OVER ( ORDER BY COL1, COL2 ,RN ) cumulative_tot
FROM
B
COL1 COL2 COL3 RN CUMULATIVE_TOT
1 A 2 1 2
1 A 2 2 2
1 A 2 3 2
1 B 3 1 5
1 B 3 2 5
1 C 5 1 10
1 D 2 1 12
1 D 2 2 12
8 rows selected Regards,
Peter -
Keeping a Running Total for Formula fields
Post Author: khanh
CA Forum: Formula
I've been messing around for the past couple of days trying to figure out what the best approach for my problem. So here is what I'm trying to accomplish. I have multiple rows which contains sums for different columns and one of the columns contains the maximum of the sums.
For example:
ROW 1 SUM (A) SUM(B) SUM(C) MAX(sum(a), sum(b), sum(c))<----
Formula Variable 1
ROW 2 SUM (A) SUM(B) SUM(C) MAX(sum(a), sum(b), sum(c))<----
Formula Variable 2
ROW Total SUM (1A2A) SUM(1B2B) SUM(1C+2C) Result of Row 1 + Result of Row 2
What I did was create a formula variable that evaluates the maximum of those rows and have a summary row, that keeps a running total. I'm not sure how to store the result of that formula variable in the running total since the formula variable isn't an option to select. Does anyone have a suggestions if this is a good approach or if there's another way to approach it?For each value you enter into scores.text, end it with a
+"\n"
as in...
scores.text = String(1100) + "\n";
scores.text += String(2200) + "\n";
scores.text += String(1500) + "\n"; -
CALCULATE RUNNING TOTALS FOR SUBSETS OF THE DATA IN A SECTION
How can I calculate a running total in BO XI Release 2, (WebI), where my totals only include the value of the current row and the previous 5 rows?
For Example:
In the data, behind my BO table, I have transaction dates that roll up to a dimension called Period. The "Period" represents the Year and Month of the transaction date, which is a month's worth of data at a time. Each month contains an aggregated value that is the Population of items for that month. The RunningSum function in BO works well, except that I need the running total to only include the current month along with the last 5 months, for a total of 6 months worth of data per row.
See my example below. The Period of JAN 2009 includes the Population for JAN 2009 plus the sum of the Populations from AUG 2008 through DEC 2008 for a total of 6 months worth of data. FEB 2009 includes SEP 2008 through FEB 2009. MAR 2009 includes OCT 2008 through MAR 2009...
__________Period_______Population_______6 MOS
__________200801__________54___________54
__________200802__________60__________114
__________200803__________50__________164
__________200804__________61__________225
__________200805__________65__________290
__________200806__________58__________348
__________200807__________70__________364
__________200808__________64__________368
__________200809__________59__________377
__________200810__________62__________378
__________200811__________66__________379
__________200812__________75__________396
__________200901__________62__________388
__________200902__________53__________377
__________200903__________63__________381
__________200904__________67__________386
Six months is obviously no magic number. I'd like the solution to be flexible enough to use for 3, 12, 18, or 24 month periods as well.Hi Frank,
can you consider building the rolling sums directly in your database using subselects in the select statement:
eg. select attr1, attr2,key2, (select sum(key1) from B where B.month<=A.month and B.month>=A.month-6) from A
Just create a key figure in your universe and add the subselect statement select sum(key1) from B where B.month<=A.month and B.month>=A.month-6 as select-clause.
ATTENTION: This is SQL pseudo code.
Regards,
Stratos -
Running total for item availbe qty. from On Hand - SO + PO by promise date
I stuck with Balance(running total).
How to link item number with SO and PO?
Need daily item qty. available qty from "On Hand" Qty. + PO - SO by promise date and sort by ascending?
Item# Order Date SO/PO PromiseDate Qty Bal.
AE01 08/01/08 OnHand 20 20
08/02/08 SO#1877 08/05/08 -3 17
08/04/08 SO#2044 08/08/08 -6 11
07/22/08 PO#632 08/10/08 10 21
Thanks.create a group by promise date
2nd group by po#
put the fields either in the group or in the details
PO#, PO promise date, qty and SO#, SO promise date, qty then availability qty
manual running totals
create 3 formulas
1 reset
WHILEPRINTINGRECORDS;
NUMBERVAR ITEMLOC := 0;
place in the group header on what you want the total to reset by (po#)
1 calc
WHILEPRINTINGRECORDS;
NUMBERVAR ITEMLOC := ITEMLOC +(qty};
this gets placed where the calculate will take place (next to qty)
1 display
WHILEPRINTINGRECORDS;
NUMBERVAR ITEMLOC;
ITEMLOC
this gets placed in the group footer.
for each field that gets calculated by a group create 3 formulas for each
they need to have the same variable name to reference each other.
if you need to create a 2nd set to calc something else give that a new variable name. -
SQL: delete command for duplicate rows for any particular user
Hello Experts,
I've a table like below, where 'X' is the primary key.
X Y Z
a | p | amit
b | q | amit
c | r | amit
d | p | amit
e | s | amit
f | p | manish
g | t | manish
h | p | akash
Objective:
Find and delete all the rows who has duplicates (for 'Y') for user 'amit'. Here, 'p' is given as an example. We don't know what the actual duplicate value is.
Expected Result:
rows 'a' and 'd' should be deleted
SQL:
===
select Y, count(*) from T where Z='amit'
group by Y
having count(Y) >1
This query works to get the duplicates and the total count.
However, how to delete these rows from actual table is the question. Please note that I need to run this query through a JDBC program.
Thanks,You could try
delete from tableb
where x not in ( select max(s.x)
from tableb s
group by s.y, s.z);The easiest way I've found to build these sort of statements is to write a select first which gives you the records you want ( or not want in this case ). Then to write the delete round that statement.
Edited by: Nigel Ren on 07-May-2011 01:23 -
SQL Plus: Check for duplicate rows
Hi.
Let say I have a table called HISTORY.
I have 3 fields in this table(EQ_NO, HISTORY_TYPE, REC_TIME_IN)
Sample data:
ABC123,REC,12:05
ABC123,STA,12:05
ABC123,DIS,12:00
XYZ123,REC,12:05
XYZ123,STA,12:05
XYZ123,DIS,11:00
Question:
How to select the data where its REC_TIME_IN is/are not equal to same EQ_NO and HISTORY_TYPE = 'REC') ??
Thanks.If I understood well, if the data be like this :
ABC123,REC,12:05
ABC123,REC,13:05
ABC123,STA,12:05
ABC123,STA,12:05
ABC123,DIS,12:00
XYZ123,REC,10:05
XYZ123,REC,12:05
XYZ123,STA,12:05
XYZ123,DIS,11:00
The query result should be :
ABC123,REC,12:05
ABC123,REC,13:05
XYZ123,REC,10:05
XYZ123,REC,12:05
If so :
create table test(
EQ_NO varchar2(10),
HISTORY_TYPE char(3),
REC_TIME_IN varchar(10))
insert into test values('ABC123','REC','12:05' );
insert into test values('ABC123','REC','13:05' );
insert into test values('ABC123','STA','12:05' );
insert into test values('ABC123','STA','12:05' );
insert into test values('ABC123','DST','12:00' );
insert into test values('XYZ123','REC','10:05' );
insert into test values('XYZ123','REC','12:05' );
insert into test values('XYZ123','STA','12:05' );
insert into test values('XYZ123','DIS','11:05' );
select a.*
from test a
where eq_no||history_type
in (select eq_no||history_type
from test b
where a.rec_time_in = b.rec_time_in )
AND history_type = 'REC' -
How do I put a running total in a Reports 6i Report?
I need to write a report which shows a running total at the foot of each page. The report is a series of (potentially) multi-page sections each formatted like this:
Page 1
======
Tom £100
Dick £150
Harry £100
Sub Total £350
Page 2
======
Peter £200
Paul £50
Mary £100
Total £700
Lines are of variable height, so I can't predict how many there'll be on a page.
The help system just tells me to "use a summary field". Yeah, right. Can anybody give me some more detailed instructions?
-- Chris HuntThanks for that.
I didn't really express the problem as well as I might have done, as the Sub-Total needs to be the sum of all the items on the current page and on all preceeding pages. resetting on page just gives you the total for that page.
I did find a way to do it. First you set up a summary field in the same group as the data lines, summing the amount and resetting on the parent group. This gives you a running total for each row:
Page 1
======
Tom £100 £100
Dick £150 £250
Harry £100 £350
Page 2
======
Peter £200 £550
Paul £50 £600
Mary £100 £700
You don't actually output this summary field in the prinout (except when debugging :-) ). Now create a summary field at the foot of the page, or in the margin. Set its value to the Max() of the running total summary, resetting on page. That gives you the amount required, assuming all individual amounts are positive.
If it's possible to have negative amounts, I expect that using Last() instead of Max() for the page summary would do the trick. -
is there any method to create row wise running total in Crystal Reports?
>
gourav.sengupta wrote:
> Hi,
>
> I needed a running total but for rows. Therefore if the data set is in the following manner:
>
> Column 1 Column 2 Column 3 Column 4
> A 12 13 14
> B 11 10 19
>
> The the running total will appear as:
> RT 23 23 33
>
>
> Thanks and Regards,
> Gourav
I am confused as to what you want.
Your sample shows sums for collumns, not rows. You do not need a running total for this, just sum them.
If you want to total each row, make a formula that adds them up and place on the row. -
Order top down for a running total
HI Is it possible to do this. I have a running total for the amt column of the row. There is one group, the transaction code. is it possible to order the data according to the amount column from high to low?
hi Paul,
a group cannot unfortunately be sorted on anything that is considered whileprintingrecords...e.g. running totals, shared vars.
however, if this is a requirement then you can pass the sort criteria to a subreport and then use the subreport to display your data. the subreport is then sorted using this criteria (rolled up in a string running total) and the main report is suppressed.
as an example, have a look at the attachment...extract the contents and change the .txt extension to .rpt. there are some instructions on the report as to how to use the above technique.
your other choice is to create the report off of a Command object and create the running total in the command object.
SQL Expressions can sometimes be used (depending on your database) to bring in RT data but require a Select statement inside the expression which is unfortunately not supported. so a Command would be recommended should you wish to do this with SQL.
cheers,
jamie -
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 -
Running total of another running total ( or some other solution )
I posted in my previous thread that I would like to be able to do rounding at the subtotal level and then have a total of these subtotals. Here is the original thread:
totals in a cross tab report
So I was told that with the cross-tab report I can either do rounding at the details level or at the final total level. However, I need to be able to do the following:
Suppose I receive payments from different states. In my report I would like to be able to display:
- a total of all payments for one given state, rounded to whole dollars - this one is easy because I just create a running total for the payments and then at the end I round it to whole dollars
- a total of all payments and all states as one number. However, the problem I can't figure out here is that this grand total needs to be calculated as the SUM of the totals for each state where the total for each state is rounded to a whole dollar before being added to the grand total. So the rounding should not be done on the final grand total but rather:
1. calculate the total of payments for one state and round it to a whole dollar - let's call it StateTotal ( rounded)
2. calculate the SUM of all StateTotal values. So it needs to be a SUM of the already rounded state totals.
Any help will be greatly appreciated.
thankshello all,
if you want to use a manual running total then that is okay. you don't actually put the manual running total in the cross-tab expert though as you will get a print time error.
you use the "Display String" formula dialogue on an existing cross-tab summary to do the manual running total in.
have a look at the attached sample...there are 2 manual running totals in there...one that goes horizontally (across the columns) and one that goes vertically (down the rows).
there is also a Xtab Info column that is there just to show you how the manual running total counter variables are incremented through the cross-tab. in crystal reports 2008 there are a lot of new cross-tab functions that are different from this but that is a completely different topic.
i hope this helps,
jamie -
Cumulative Balance Running Total
Hello community,
i am doing a business partner Account balance report, i have already successfully fetch my data in to crystal reports as well as the running total for the cumulative balance, my problem is i have a duplicated rows in debit side, now how will i say to crystal reports (in Formula expression) that the 1st line if duplicated will the only one to be evaluated. for more detail please see image below
http://i264.photobucket.com/albums/ii184/abing430/CRDuplicatedRows.png
http://i264.photobucket.com/albums/ii184/abing430/CRDuplicatedRows-1.png
please help.
best regards,
Fidelhello sharonamt,
thanks for the response.
//Head
Shared NumberVar OB := {Command.Open Balance}
//Line
shared numbervar OB;
OB := OB + {BP_AccountBalance;1.Credit} - {BP_AccountBalance;1.Debit}
//Footer
Shared numbervar OB
i have this ff. formula the header is put in the page header, the line is put ing Group Footer section and the footer is put in report footer section. my group is grouped by Ref field w/c is unique in this report.
the duplicated rows is eliminated since i put my line formula in the group footer. but using the ff. formula's the report is ok, the results is fine on the first page only, because in the second page it will get the OB balance which is in the page header of the report., i dont needt to reset my running total.
thanks.
please help
best regards.
EDIT:
i have manage to figure out my problem... i just use this formula and it works.
whileprintingrecords;
if pagenumber = 1 then Shared NumberVar OB := {OpeningBalance.Open Balance}
else
0
since im having problem with reseting of the openingbalance, i had trap the page numvber and never reset the running total. this formula works for me as of now.
Fidel
Edited by: Avelino Fidel on Jan 24, 2011 2:46 PM -
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.
ThanksPost 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. -
Oracle report running total Resseting balance
Dear All,
I am developing report on Oracle R12 fixed Assets, I have to calculate the running total for each asset.
In brief
Asset 1
cost Deprciation Adjusted Cost
50 - 2 48
48 -5 45
45 - 4 41
I achieved that by using
if :p_val is null then
:result := nvl(:cost,0)-nvl(:depriciation,0);
:P_val :='5';
return :result;
else
:result := nvl(:result,0)-nvl(:depriciation,0) ;
return :result;
end if;
working fine
But problem is when the next asset start on same report
Asset 2
cost Deprciation Adjusted Cost
100 5 36
it substracts the last total (running total of previous asset with depriciation which was 41 in this example).
Oracle Champs pl advice me how to solve this.
I really dont got any idea how to solve this.
thanksDear,
Thanks for your reply , in your reply what you said I tried this but in pl/sql I am not actually achieving the result. The balance is not resetting at next group if you give one accurate line it would be really helpfull.
thanks
Maybe you are looking for
-
Hi, I am having an Interface Mapping involving two mapping programs in the following sequence: 1) Message Mapping 2) Java Mapping There are two Message Interfaces on the source side and one MI on the target side. Now the problem is that only the Java
-
Yosemite scheduled start up not really starting up
I updated to Yosemite and it seems that schedules start up (via System Preferences > Energy Saver > Programmed....) is not really booting the system up. I Mavericks and before, the computer started, booted, loaded everything that it was supposed to,
-
Is there a program like WiseStamp for iMail?
Anyone have a program that is comparable that works on a Mac?
-
Console bouncing erratically (earlier post marked answered prematurely)
Sorry about this apparent double post. Asked earlier why Console, opened, and set to bounce, wasn't bouncing. I don't want to add this to the earlier post, since, as it's marked answered, I don't think anyone will notice it there any more. http://dis
-
Formula in Numbers - returning values
Hi, In cell A1 i wish to insert a Tick Box In cell B1 i wish to insert a value of for example $100 In cell C1 I wish the value to be either 0 or $100 ; this based whether i tick the box in cell A1. So if I don't tick the box then the value in C1 wou