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 MyRow1, MyRow1, COUNT(*) AS TotalCount FROM tblContactIncoming WHERE AdvertId = $AdvertId GROUP BY MyRow1, MyRow2"

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'];
  }

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;
      }
			//...
		}
UK Electronic Designer
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published.