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()
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With