|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stay one step ahead of the competition. Evaluate and give feedback
on some of the hottest web development tools on the market today.
Make your opinion heard! Click
Here
|
|
#1
|
|||
|
|||
|
Is there a PRODUCT() function in SQL?
Hi,
Is there a function that I can use to calculate the product of values across rows for a particular field. I want the equivalent of SUM() for multiplication. If there isn't a built in function, can anyone think of a way to calculate this product without iterating over every row in a loop? Yikes! As an example, if I have the following table: avalue 2 4 3 3 I want to calculate the product of avalue, which is 2*4*3*3 = 72. TIA |
|
#2
|
||||
|
||||
|
There is no official function, but many databases implement their own functions to add to what SQL provides. What database system are you using?
I am not sure how you could do this in just SQL. I would try and tackle this in the code |
|
#3
|
|||
|
|||
|
I'm using MySQL v3.23.46. I think for now, I will just use something like:
$sth = execSQL("SELECT * FROM daily_returns"); $totReturnPlan *= ($ref->{DailyReturn} + 1) while($ref = $sth->fetchrow_hashref()); Unless you have something more efficient... I know that it can be done in MSSQL by issuing something like: declare @x int set @x = 1 select @x = @x * (DailyReturn + 1) from daily_returns print @x Thanks |
|
#4
|
||||
|
||||
|
if you're using SQL Server 2k, create a user defined function to calculate a product.
|
|
#5
|
|||
|
|||
|
Quote:
Just about any decent DBMS can have user-defined functions or procedures, including (of course) Oracle, DB2, PostgreSQL, Interbase/Firebird, SAPDB, etc.... Actually, even MySQL has a method for doing this also, although it is more of a work-around than a true feature. And there is definitely something to be said for confining this sort of logic to the database, rather than the inefficiency of retrieving all the numbers into your application before making the calculation.
__________________
The real n-tier system: FreeBSD -> PostgreSQL -> [any_language] -> Apache -> Mozilla/XUL Amazon wishlist -- rycamor (at) gmail.com |
|
#6
|
|||
|
|||
|
Thanks for your ideas, I am especially interested in getting MySQL to handle UDFs...I'll check that out.
|
![]() |
| Viewing: Dev Shed Forums > Databases > Database Management > Is there a PRODUCT() function in SQL? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|