Search code examples
phpmysqlarrayssum

MySQL when to get the sum of multiple fields created using COUNT CASE WHEN function? Inside of same query or after with PHP?


I have a mysql query that Selects data and returns the total of multiple fields using the COUNT(CASE WHEN) function. What I would like to accomplish now is get the some of all those fields in order to see if that total is > 0 or = 0. I am just not sure if I can do this in the same MySQL query or if I should get the sum via a PHP when looping through the returned data.

Below is my QUERY and after that are ideas I thought may work but would be most appreciative if someone can show me a better/more efficient/cleaner way to get the same results.

foreach ($iconArray as $icon) {
    
     $query = "
        SELECT teacher_type, link_url, link_title,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 1 AND link_column = 1 THEN 1 END) AS location1,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 1 AND link_column = 2 THEN 1 END) AS location2,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 1 AND link_column = 3 THEN 1 END) AS location3,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 1 AND link_column = 4 THEN 1 END) AS location4,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 2 AND link_column = 1 THEN 1 END) AS location5,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 2 AND link_column = 2 THEN 1 END) AS location6,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 2 AND link_column = 3 THEN 1 END) AS location7
          FROM ww_click_tracking 
        WHERE click_date BETWEEN {$date_clause}
        AND teacher_type = {$value}";

        $result = mysqli_query($link, $query);

//HERE IS WHERE I WANT TO CHECK IF ALL OF THE LOCATIONS LOCATION 1-7 ADDED TOGETHER ARE GREATER THAN 0. IF NOT THERE IS NO REASON TO CONTINUE ON. 
  for ($i=1,$i <=7, $i++) {
      $locationTotal +=  $result['location'. $i];
  }
   if ($locationTotal > 0){
     //SOMETHING TO ACTUALLY REPORT SO CONTINUE DOING YOUR THANG!
      while($row = mysqli_fetch_array($result)){
    
      }
   //ELSE 0 THEN CURRENT ICON HAD NO CLICKS TO REPORT.
   }
} //END OF FOREACH ICON LOOP

Solution

  • You could handle this on the MySQL side by adding the following conditional summation:

    SELECT ...,
        SUM(icon_type = '{$icon}' AND (
            (row_value = 1 AND link_column BETWEEN 1 AND 4) OR
            (row_value = 2 AND link_column BETWEEN 1 AND 3)
        )) AS locationTotal