Search code examples
databasedrupaldrupal-7

Drupal - How to get SUM of rows


I want to do a simple select with a SUM of several rows in Drupal, but I can't seem to figure out how to do that. I know there are more ways to do a query in Drupal (one of them is writing the actual query, but I don't want that).

Here is the code I have:

$query = db_select("node","n");
$query->fields("n", array("nid","likes" => "SUM(likes)"));

But apparently Drupal strips my brackets and I get the following error:

1054 Unknown column 'n.SUMlikes' in 'field list'

Could anyone help me? Is there something like $query->sum()?


Solution

  • You'd be best off using an expression:

    $query = db_select('node', 'n')
      ->fields('n', array('nid'));
    $query->addExpression('SUM(likes)', 'likes');
    

    The first argument is the expression, the second the alias.

    Hope that helps