For Programmers: Free Programming Magazines  


Home > Archive > PHP SQL > May 2005 > adding SUM to query









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author adding SUM to query
Chris

2005-05-28, 3:56 pm

I have a SELECT * query that returns info such as 'name', 'date',
'cost', and 'notes'. At the head of this query return it reads how
many records were found. I would like to append that with 'how many
records were found at a cost of' ...

But haven't been able to find a means of totalizing the 'cost' column
in my query. Does anyone have any ideas on how this might be
accomplished ??? I've spent considerable time on the net looking at
examples and my reference book but so far, no luck.

TIA,
Chris
Malcolm Dew-Jones

2005-05-28, 8:56 pm

Chris (coverland914@yahoo.com) wrote:
: I have a SELECT * query that returns info such as 'name', 'date',
: 'cost', and 'notes'. At the head of this query return it reads how
: many records were found. I would like to append that with 'how many
: records were found at a cost of' ...

: But haven't been able to find a means of totalizing the 'cost' column
: in my query. Does anyone have any ideas on how this might be
: accomplished ??? I've spent considerable time on the net looking at
: examples and my reference book but so far, no luck.

The row count you see is extra information, it is not part of the query,
and what sort of information you can get depends on the application you
are using. Something like mysql will give you basic feedback such as the
row count. If you used a report application then you could ask the report
application to provide a sum at the end, but otherwise you have to
calculate it your self. If you used a report application then it would
simply be doing something like what I describe below.


There are two basic ways to do it your self

-1- do the sum yourself as you scan through the rows
(pseudo code, based on some mysql/php examples I have)

$sum = 0;
while($row = mysql_fetch_array($sth))
{
$sum += $row[cost];
Print_the_row($row);
}
Print_the_cost($sum);


-2- or use two queries


mysql> select * from query;
mysql> select sum(cost) from query;



--

This space not for rent.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com