Conditional sum
Conditional sum
andreavellone
Posts: 46Questions: 13Answers: 2
I had to sum the values only if other values are the same.
I have a table like this
item_id quantity
1 10
2 7
1 12
3 5
2 11
1 3
I had to sum the quantity with the same item_id
so: item_id (1) =sum(10, 12, 3)
First of all, it's possible using render?
Or i must use some Php function?
Thank a lot for any ideas
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
You can use this: https://datatables.net/reference/api/rows().every()
You can do anything in the function that it provides. See the last example on that page.
In addition here is an example from my own coding in which I set all values for a certain column.
Forgot mention: I do all of this triggered by the "draw" event. Subsequently the column is being rendered like any other column.
Its possible to be more concise with the DataTables API as well: you could use
rows().data()
to get the data for the row, thenfilter()
to filter it down to just item_id 1 and usepluck()
to get the value for the quantity and finally thesum()
plug-in to get the summation.Allan
I tried something like this:
{ data: "ol", editField: "movimenti.ad_ol_id", render: function ( data, type, row ) {
return data.id +' '+ data.fase +' '+data.centrale+'('+data.filter( function ( d ) { return d.materiale_id == 66;} ).pluck( 'var' ).sum();+')';}},
but the answer is "data.filter is not a function"...
any ideas?
In this case
data
is not a DT API which is why you are getting the error. I think the best place for this is in thedrawCallback
function so it an calculate your totals each time Datatables draws the table.Kevin