I am trying to figure out how to implement the OLAP operation Roll-up in Cypher. I am stuck with finding how to create a node and then assign it the sum of a column of a table in Cypher. More particularly, I am trying to achieve this result : Code result [EDITED] With this code I am obtaining the result as seen in the picture :
MATCH(p:Product)
WITH sum(p.unitsInStock) as SommeUnits, p.supplierID as Supplier, p.reorderLevel as ReordLevel
CREATE(reord:Product {productName : "TotalReord", unitsInStock : SommeUnits})
RETURN ReordLevel,Supplier, SommeUnits
ORDER BY ReordLevel
Relationships : Supplier-[:SUPPLIES]->(Product) Attributs of Product : unitsInStock, productName, productId, unitsInOrder, supplierID
The problem is that this code is not working properly because it generates not just one node but multiples, and the result that I get is obtained only if I play the query twice.
Aggregating functions like
SUMuse the non-aggregated items in the same (WITHorRETURN) clause as "grouping keys". So, yourWITHclause is generating aSommeUnitsvalue for each distinctSommeUnits/ReordLevelcombination. And yourCREATEis being called for eachSommeUnitsvalue.This query should work properly (assuming that you want every returned record to have the same
SommeUnitsvalue):This query uses
MERGEto avoid creating duplicate "TotalReord" nodes every time you call this query. And theWHEREclause filters out the "TotalReord" node, so that its existingunitsInStockvalue will not be used when calculating the new sum, inflating it.If you actually want each returned record to have the sum just for that record's
SommeUnits/ReordLevelcombination, you can do this:[UPDATED]
Finally, if you want to do the previous query but also get the overall total, this query will show the overall total as the fourth value in each returned record: