I am struggling to make a query in a custom service function in Drupal 7, which should make 3 sums. In each table (3), there are 2 records saved with the following values:

  • field_data_field_monto_15pts with field [field_monto_15pts_value] data: 5 and 6
  • field_data_field_monto_14pts with field [field_monto_14pts_value] data: 3 and 4
  • field_data_field_monto_13pts with field [field_monto_13pts_value] data: 1 and 2

The service function that performs the query and returns data in the JSON format is the following.

$cantidad = db_query('
  SELECT SUM(field_monto_15pts_value) AS 15pts,  
         SUM(field_monto_14pts_value) AS 14pts,  
         SUM(field_monto_13pts_value) AS 13pts  
  FROM {field_data_field_monto_15pts},  {field_data_field_monto_14pts},  {field_data_field_monto_13pts}')  

return $cantidad;  

What I expect from the function is the following values.

  "15pts": "11",
   "14pts": "7",  
   "13pts": "3"  

What the function returns is this.

   "15pts": "44",  
   "14pts": "28",  
   "13pts": "12"  

What is wrong in the code I am using?


Well ... Since no one had this problem, or nobody has a solution, I put the solution that I have given on the site https://www.drupal.org/node/2898276

The problem is how I wrote the query to the database. A Cartesian product is produced. After rewriting the query was solved. It was finally written:

$lo_que_che= db_query('SELECT (SELECT SUM(field_monto_15pts_value) AS 15pts FROM {field_data_field_monto_15pts}) 15pts, (SELECT SUM(field_monto_14pts_value) AS 14pts FROM {field_data_field_monto_14pts}) 14pts, SUM(field_monto_13pts_value) AS 13pts FROM field_data_field_monto_13pts}') ->fetchAssoc();  return $lo_que_che;  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.