Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 332
Eduard Luca Avatar asked Aug 31 '11 12:08

Eduard Luca


1 Answers

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

like image 180
Clive Avatar answered Nov 03 '22 07:11

Clive