Get a single result for each MyColumnName value that matches the search criteria

For example, say you have multiple rows where MyColumnName=1 that each matches the query, you’ll get back just one result with MyColumnName=1

  //Get every MyColumnName that matches regardless of on how many rows, returned only once
  $sql = "SELECT MyColumnName
                          FROM {$wpdb->prefix}my_table_name 
                          WHERE Something = "ABC"
                          GROUP BY MyColumnName
                        ";
  if (current_user_can('administrator'))
    $wpdb->show_errors();
  $Results = $wpdb->get_results($sql, ARRAY_A);
  if (count($Results) == 0)
    return(False);

  foreach ($Results as $Result)
  {
    $MyColumnName = $Result['MyColumnName'];
    
  
  }
Same but with an additional field that tells you how many rows matched for each MyColumnName
"SELECT MyColumnName, COUNT(*) AS TotalCount from wp_my_table_name WHERE Something="ABC" GROUP BY MyColumnName;"

COUNT and GROUP BY in same query

Good example:

https://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-count-with-group-by.php

Getting total count of results based on multiple groupings
"SELECT MyColumnName1, MyColumnName2, COUNT(*) AS TotalCount FROM tblContactIncoming WHERE AdvertId = $AdvertId GROUP BY MyColumnName1, MyColumnName2"

This will return an individual TotalCount result for every combination of MyRow1 and MyRow2 found.

If you add TotalCount together for all of the results returned you’ll get the total as if the GROUP BY was not there, as you’d expect. An example usage:

  $TotalRows = 0
  $TotalRowsMatchingSpecificValues
  foreach ($Results as $Result)
  {
    $TotalRows += $Result['TotalCount'];
    if ( ($Result['MyRow1'] == 10) && ($Result['MyRow2'] == 12)
      $TotalRowsMatchingSpecificValues += $Result['TotalCount'];
  }

GROUP BY multiple columns

SELECT * FROM MyTable
GROUP BY MyColumn1, MyColumn2, MyColumn3

The results will first be grouped by MyColumn1, then by MyColumn2, etc. In MySQL, column preference goes from left to right.

Below here This is PHP4 Code!

IMPORTANT NOTE ABOUT GROUP BY

The fields you get returned are not necessarily the fields from the exact same row in a collection of group by rows.  This is relevant when you for instance want to get the first occurrence of something within the group by, i.e. the row with the earliest datetime value (which wasn’t used to group by).  In this situation you can’t rely on the GROUP BY to give you that. The ORDER BY you use will have no effect on the aggregation performed by the GROUP BY as it is only applied afterwards on the results of the GROUP BY.  The values returned have to be assumed to be from a random row / rows within the group.  There is a solution however – see below

How To Get Sort Within A Group By

Example of how to get the earliest datetime row value within a GROUP BY:

	Command1->CommandText = "SELECT LogMeltCode, MIN(LogDateTime) as LogDateTime, LogLotNo, LogWorker, LogInstrumentNo \
								FROM tblLogEvents \
								GROUP BY LogMeltCode, LogLotNo, LogWorker, LogInstrumentNo \
								ORDER BY " + SearchOrderBy;
	//The MIN() above ensures we get the earliest occurance of that field

Simple Single Field Group By Example

	$query = "SELECT *, COUNT(SchoolUid), SUM(ProjectIsActive) , MAX(ProjectStartDate) FROM tblMyTable
             WHERE DATE_SUB(CURDATE(),INTERVAL 90 DAY) <= LastUpdated
						 GROUP BY SchoolUid
						 ORDER BY SchoolName ASC";
	$result = mysqli_query($database1, $query); 
	$NumberOfResults = mysqli_num_rows($result);

    while ($row = mysqli_fetch_assoc($result))
    {
      foreach ($row as $key => $value)
			{
					if ($key == "SomeRowName")
						$SomeRowName = $value;
					else if ($key == "SUM(ProjectIsActive)")
						$NoOfActiveProjects = $value;
					else if ($key == "COUNT(SchoolUid)")
						$NoOfProjects = $value;
					else if ($key == "MAX(ProjectStartDate)")
						$NewestProjectStartDate = $value;
      }
			//...
		}
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *