Skip to content

Instantly share code, notes, and snippets.

@jexp
Created December 22, 2021 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jexp/434c0e83fc8b29e16bb468b4f1afd357 to your computer and use it in GitHub Desktop.
Save jexp/434c0e83fc8b29e16bb468b4f1afd357 to your computer and use it in GitHub Desktop.
Select Average Value of Records with a Max Date in Cypher

Select Average Value of Records with a Max Date in Cypher

Question: Oddman

Hmmmm. How would I go about getting the average of a value for a given date, for all records? Ie. For all records on a given date, I want the highest value on that date, and then average that value across all the results.

in SQL, it'd be something like avg... select max... group by date

Answer: Michael

if you have indexes on date and value this one should be quite efficient, see PROFILE

MATCH (r:Record) WITH max(r.date) as max
MATCH (r:Record) WHERE r.date = max
RETURN avg(r.value)

or to avoid the double read but use some more memory

MATCH (r:Record) WITH r.date as date, collect(r) as records ORDER BY date DESC LIMIT 1
UNWIND records as r
RETURN avg(r.value)

or this but it might be more expensive due to the early reads

MATCH (r:Record) 
RETURN r.date, apoc.coll.avg(collect(r.value)) as avg ORDER BY r.date DESC LIMIT 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment