Getting average of calculated columns

Posts   
 
    
gabrielk avatar
gabrielk
User
Posts: 231
Joined: 01-Feb-2005
# Posted on: 10-Aug-2009 12:33:11   

C# 3.5, LLBLGen 2.6, SelfServicing

Hi,

I want to do a scalar function with a calulated field, but have no clue where to start.

I've got a table to track purchases (always for the same item, therefore no Product) with the following columns: Quantity & Price.

What I want to get out of the table is the average price per unit bought.

I can only describe my formula, for which I want to get the LLBLGen code, like this:

'Get the sum of Quantity*Price of each row and divide it by the sum of Quantity for all rows.'

Of course it's easy to do this in code, but I prefer to get it directly queried from the DB.

Any suggetions?

Thanks, Gab

Walaa avatar
Walaa
Support Team
Posts: 14993
Joined: 21-Aug-2005
# Posted on: 10-Aug-2009 14:38:13   

So basicly you want something like:

SELECT SUM(Quantity * UnitPrice)/Sum(Quantity) 
FROM [Order details]

Right?

(EDIT)

You can make use of constants in DBFunctionCalls.

ResultsetFields fields = new ResultsetFields(1);
fields.DefineField(OrderDetailsFields.Id, 0);

fields[0].ExpressionToApply = new DbFunctionCall(
    "SUM({0} * {1})/SUM({0})", 
    new object[] { OrderDetailsFields.Quantity, OrderDetailsFields.UnitPrice});