{"id":1580,"date":"2015-02-27T10:41:51","date_gmt":"2015-02-27T10:41:51","guid":{"rendered":"https:\/\/ibex.tech\/cloud\/?p=1580"},"modified":"2023-10-30T15:05:29","modified_gmt":"2023-10-30T15:05:29","slug":"group-by-2","status":"publish","type":"post","link":"https:\/\/ibex.tech\/cloud\/mysql\/queries\/select\/group-by-2","title":{"rendered":"GROUP BY"},"content":{"rendered":"\n<h4 class=\"wp-block-heading\">Get a single result for each MyColumnName value that matches the search criteria<\/h4>\n\n\n\n<p>For example, say you have multiple rows where MyColumnName=1 that each matches the query, you&#8217;ll get back just one result with MyColumnName=1<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  \/\/Get every MyColumnName that matches regardless of on how many rows, returned only once\n  $sql = \"SELECT MyColumnName\n                          FROM {$wpdb-&gt;prefix}my_table_name \n                          WHERE Something = \"ABC\"\n                          GROUP BY MyColumnName\n                        \";\n  if (current_user_can('administrator'))\n    $wpdb-&gt;show_errors();\n  $Results = $wpdb-&gt;get_results($sql, ARRAY_A);\n  if (count($Results) == 0)\n    return(False);\n\n  foreach ($Results as $Result)\n  {\n    $MyColumnName = $Result&#91;'MyColumnName'];\n    \n  \n  }<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\">Same but with an additional field that tells you how many rows matched for each MyColumnName<\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>\"SELECT MyColumnName, COUNT(*) AS TotalCount from wp_my_table_name WHERE Something=\"ABC\" GROUP BY MyColumnName;\"<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">COUNT and GROUP BY in same query<\/h4>\n\n\n\n<p>Good example:<\/p>\n\n\n\n<p><a href=\"https:\/\/www.w3resource.com\/mysql\/aggregate-functions-and-grouping\/aggregate-functions-and-grouping-count-with-group-by.php\">https:\/\/www.w3resource.com\/mysql\/aggregate-functions-and-grouping\/aggregate-functions-and-grouping-count-with-group-by.php<\/a><\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Getting total count of results based on multiple groupings<\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>\"SELECT MyColumnName1, MyColumnName2, COUNT(*) AS TotalCount FROM tblContactIncoming WHERE AdvertId = $AdvertId GROUP BY MyColumnName1, MyColumnName2\"<\/code><\/pre>\n\n\n\n<p>This will return an individual TotalCount result for every combination of MyRow1 and MyRow2 found.<\/p>\n\n\n\n<p>If you add TotalCount together for all of the results returned you&#8217;ll get the total as if the GROUP BY was not there, as you&#8217;d expect.  An example usage:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  $TotalRows = 0\n  $TotalRowsMatchingSpecificValues\n  foreach ($Results as $Result)\n  {\n    $TotalRows += $Result&#91;'TotalCount'];\n    if ( ($Result&#91;'MyRow1'] == 10) &amp;&amp; ($Result&#91;'MyRow2'] == 12)\n      $TotalRowsMatchingSpecificValues += $Result&#91;'TotalCount'];\n  }<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">GROUP BY multiple columns<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT * FROM MyTable\r\nGROUP BY MyColumn1, MyColumn2, MyColumn3<\/code><\/pre>\n\n\n\n<p>The results will first be grouped by MyColumn1, then by MyColumn2, etc. In MySQL, column preference goes from left to right.<\/p>\n\n\n\n<p><span style=\"color: #ff0000;\"><em><strong>Below here This is PHP4 Code!<\/strong><\/em><\/span><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">IMPORTANT NOTE ABOUT GROUP BY<\/h4>\n\n\n\n<p>The fields you get returned are not necessarily the fields from the exact same row in a collection of group by rows. &nbsp;This is relevant when you for instance&nbsp;want to get the first occurrence of something within the group by, i.e. the row with the earliest datetime value (which wasn&#8217;t used to group by). &nbsp;In this situation you can&#8217;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. &nbsp;The values returned have to be assumed to be from a random row \/ rows within the group. &nbsp;There is a solution however &#8211; see below<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">How To Get Sort Within A Group By<\/h4>\n\n\n\n<p>Example of how to get the earliest datetime row value within a GROUP BY:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\tCommand1-&gt;CommandText = \"SELECT LogMeltCode, MIN(LogDateTime) as LogDateTime, LogLotNo, LogWorker, LogInstrumentNo \\\n\t\t\t\t\t\t\t\tFROM tblLogEvents \\\n\t\t\t\t\t\t\t\tGROUP BY LogMeltCode, LogLotNo, LogWorker, LogInstrumentNo \\\n\t\t\t\t\t\t\t\tORDER BY \" + SearchOrderBy;\n\t\/\/The MIN() above ensures we get the earliest occurance of that field<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Simple Single Field Group By Example<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>\t$query = \"SELECT *, COUNT(SchoolUid), SUM(ProjectIsActive) , MAX(ProjectStartDate) FROM tblMyTable\n             WHERE DATE_SUB(CURDATE(),INTERVAL 90 DAY) &lt;= LastUpdated\n\t\t\t\t\t\t GROUP BY SchoolUid\n\t\t\t\t\t\t ORDER BY SchoolName ASC\";\n\t$result = mysqli_query($database1, $query); \n\t$NumberOfResults = mysqli_num_rows($result);\n\n    while ($row = mysqli_fetch_assoc($result))\n    {\n      foreach ($row as $key =&gt; $value)\n\t\t\t{\n\t\t\t\t\tif ($key == \"SomeRowName\")\n\t\t\t\t\t\t$SomeRowName = $value;\n\t\t\t\t\telse if ($key == \"SUM(ProjectIsActive)\")\n\t\t\t\t\t\t$NoOfActiveProjects = $value;\n\t\t\t\t\telse if ($key == \"COUNT(SchoolUid)\")\n\t\t\t\t\t\t$NoOfProjects = $value;\n\t\t\t\t\telse if ($key == \"MAX(ProjectStartDate)\")\n\t\t\t\t\t\t$NewestProjectStartDate = $value;\n      }\n\t\t\t\/\/...\n\t\t}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>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&#8217;ll get back just one result with MyColumnName=1 Same but with an additional field that tells you how many rows matched for each MyColumnName COUNT and GROUP BY [&hellip;]<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[64],"tags":[],"class_list":["post-1580","post","type-post","status-publish","format-standard","hentry","category-select"],"_links":{"self":[{"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/posts\/1580","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/comments?post=1580"}],"version-history":[{"count":14,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/posts\/1580\/revisions"}],"predecessor-version":[{"id":4542,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/posts\/1580\/revisions\/4542"}],"wp:attachment":[{"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/media?parent=1580"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/categories?post=1580"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/tags?post=1580"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}