Calculate the total ...

# Thread: Calculate the total ...

1. Senior Member
Join Date
Dec 1969
Posts
1,100

## Calculate the total ...

Hi,<BR><BR>I need to calculate the total price of the quantities in a loop<BR>"while not rs.eof then<BR><BR>response.write rsorder("priceperunit") & rsorder("qty")<BR><BR>rs.movenext<BR>wend"<BR><BR> How can I achieve that?<BR>My code:<BR>---------<BR>subtotal=0<BR>subtotal=subtotal+(rsorder("pric eperunit") * rsorder("qty"))<BR>tax=subtotal*taxrate/100<BR>----------<BR><BR>Placed in the "while not..." statement it calculates the last number (price) shown.<BR>Placed outside it give s me an exception error.<BR><BR>Thanks,<BR>Mircea<BR>

2. God
Senior Member
Join Date
Dec 1969
Posts
18,177

## RE: Calculate the total ...

Only initialize the subtotal variable once -- BEFORE the loop.<BR><BR>subtotal = 0<BR>while not rs.eof<BR>subtotal = subtotal + (rsorder("priceperunit") * rsorder("qty"))<BR>tax= tax + (subtotal * taxrate / 100)<BR><BR> rs.movenext<BR>wend<BR><BR>But, you should be able to use SQL to do the totalling for you. Look up aggregate functions.

3. Senior Member
Join Date
Dec 1969
Posts
96,118

## You are resetting...

...the subtotal back to zero every time! You must set it to zero ONLY ONE TIME, before the loop.<BR><BR>&#060;%<BR>...<BR>subtotal=0<BR><BR>w hile not rs.eof then<BR><BR> response.write rsorder("priceperunit") & rsorder("qty")<BR> subtotal=subtotal+(rsorder("priceperunit") * rsorder("qty"))<BR><BR> rs.movenext<BR>wend<BR><BR>&#039; you can calculate the tax inside the loop but there&#039;s no<BR>&#039; point, since it will change each time...wait until you get<BR>&#039; the final subtotal and then do it:<BR>tax = subtotal * taxrate / 100<BR><BR>...<BR>%&#062;<BR>

4. Senior Member
Join Date
Dec 1969
Posts
96,118

## I disagree...

&#062; you should be able to use SQL to do the totalling for you<BR><BR>Yeah, you can. But then you have to make *TWO* queries. (Since you can&#039;t use an aggregate function at the same time you are getting detail records. And let&#039;s not confuse beginners with doing a UNION or multiple record sets ugly stuff like that.)<BR><BR>And the overhead of doing a second query is MUCH higher than the simple process of accumulating a subtotal as you traipse through the records, anyway.<BR><BR>

5. Senior Member
Join Date
Dec 1969
Posts
1,100

## RE: Calculate the total ...

Thanks.<BR><BR>It worked. <BR><BR>Mircea

6. Senior Member
Join Date
Dec 1969
Posts
1,100

## RE: I disagree...

Actually, I have two INNER JOINS in my query.<BR><BR>So, I did like you and god said.<BR><BR>Thanks,<BR>Mircea

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•