So I have this sql code in Drupal:
$query = db_query('SELECT wpv.nid, n.title, AVG(vote) average FROM {wp_votes} wpv
LEFT JOIN {node} n on wpv.nid = n.nid
GROUP BY wpv.nid
ORDER BY average DESC
LIMIT 3');
It works just fine, but I need to write it with db_select:
$query2 = db_select('wp_votes','wpv');
$query2->join('node','n','wpv.nid = n.nid');
$query2->fields('wpv',array('nid','vote'));
$query2->fields('n',array('title'));
$rez = $query2->execute()->fetchAll();
My problem is that I don’t know how I can get the average vote(votes are 1,2 or 3).
How do i rewrite the part with AVG(vote). I tried with addEXpression(‘AVG(vote)’) but it didn’t work as expected, I got the average for all the entries, not just for those with the same id.
Thanks.
For AVG you need to use addExpression() and groupBy and you will have something like this
I’m not sure about sorting by $alias, but theoretical, it should work.