SUM in Server script
SUM in Server script

Hello,
I would like to know how to do SUM on a joined table ?
example:
Editor::inst( $db, 'A')
->fields(
Field::inst( 'id' )->set( false ),
Field::inst( 'dated' ),
Field::inst( 'km' ),
Field::inst('SUM(B.amount)', 'am' )->set( false )
)
->join(
Mjoin::inst( 'B' )
->link( 'A.id', 'B.jour' )
->fields(
Field::inst( 'id' )
)
)
->process( $_POST )
->json();
How to formulate ('SUM (B.amount)'
Thank you.
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
I think you can't do that with Editor. But there is a way to do something similar. Create a field instance like this:
Of course you can also use an Mjoin to return a number of individual values to the client and then do the sum manually by adding the stuff up client side. That is cumbersome ... and not needed I think.
Here is an example from my coding. I need to get an aggregated value from a different table which I can't get through a simple join or an MJoin. Aliasing an existing sql table column is the way to do it.
If I had been a little smarter by the time I wrote this I could have written:
That also passes contract.id into the function.
Thank you rf1234,
It seemed to me that it is impossible, I am disappointed by Editor, because they are classic functions of every day ...
I am only amateur with javascript, do you think it's easier with jquery client side to recover SUM?
I already used this example with length (count) :
var jTable = $('#A').DataTable( {
dom: 'Bfrtip',
ajax: 'php/A.php',
columns: [
{data: 'dated', className: 'dt-body-center'},
{data: 'km', className: 'dt-body-center'},
{data: 'B', className: 'dt-body-center', render: function ( d ) {return d.length} }
],
Knowing that B is a Mijoin table.
I would get rid of the Mjoin in this case and use your own SQL as suggested by me above. To manually sum up a variable on the client side is not very efficient.
Ok I'll try this tomorrow
Hi,
rf1234 is correct - Editor's libraries won't let you do a sum on the Mjoined data (its actually two SQL queries which is why that isn't possible).
Instead, I'd suggest using a relatively simple rendering method on the client-side to do the summation and display the result from the Mjoined data:
Just make sure you include a field for
amount
in the field list for the Mjoin.Allan
Hi,
Thank you Allan, actually your solution works very well:
By cons I have difficulties to place:
render: $.fn.dataTable.render.number(' ', '.', 2, '',' €')
@Allen Sir,
the above function
{
data: 'B',
render: function (data, type, row) {
return data.reduce( function (accum, item) {
return accum + item.amount;
}, 0 );
}
}
produces sum of distinct values only i.e. child rows with equal amount is taken once in total. Please guide how to take all 'amount' in accumulated value.
I'm afraid I don't understand what you are looking to do. Could you show me the data you are using and also the calculation you want to perform based on that data?
Thanks,
Allan