Obtaining SUM('field') in PHP code Can't figure out how to construct a query to obtain a sum of a field programmatically. The folowing code works fine for counts:

$count = Drupal::entityQuery('node')
  -&gt;condition('type', 'artefacts')
  -&gt;condition('status', '1')
  -&gt;condition('default_langcode', 1)
  -&gt;condition('field_city', $id)
  -&gt;count()
  -&gt;execute();


but no matter how I try I can't figure out how to obtain the sum. There is a lot of examples for Drupal 7 but can't find a single one for Drupal 8. 

$sum = Drupal::entityQuery('node')
  -&gt;condition('type', 'cities')
  -&gt;condition('status', '1')
  -&gt;condition('default_langcode', 1)
  -&gt;condition('field_country', $id)
  -&gt;aggregate('sum(field_artefact_count)', 'total')
  -&gt;execute();


seems to return '1' in any circumstances. The documentation on Query class is terse to put it mildly. Apparently execute() is supposed to return an array of entity id's but what's the entity id of a single total of a table of a 1000 records?
Use QueryAggregateInterface::execute:

$result = \Drupal::entityQueryAggregate('node')
  -&gt;aggregate('nid', 'sum')
  -&gt;condition('status', NodeInterface::PUBLISHED)
  -&gt;execute();


The result returned is keyed by fieldname and aggregate function:

$sum = $result['0']['nid_sum'];