- SELECT columns Name....... from table Name
- Where condition
- Group by group_by_list
- Having condition
- Order by order_by_list



- <?php
- $con=mysql_connect("localhost","root","");
- if (!$con)
- {
- die('Could not connect: ' . mysql_error());
- }
- mysql_select_db("mysql", $con);
- print "<h2>MySQL: Simple select statement</h2>";
- $result = mysql_query("select * from emp_dtl"); // First query
- echo "<table border='1'>
- <tr>
- <th>EmpId</th>
- <th>Firstname</th>
- <th>Lastname</th>
- <th>Role</th>
- <th>Salary</th>
- </tr>";
- while($row = mysql_fetch_array($result))
- {
- echo "<tr>";
- echo "<td>" . $row['id'] . "</td>";
- echo "<td>" . $row['Firstname'] . "</td>";
- echo "<td>" . $row['Lastname'] . "</td>";
- echo "<td>" . $row['role'] . "</td>";
- echo "<td>" . $row['salary'] . "</td>";
- echo "</tr>";
- }
- echo "</table>";
- //Group by in PHP
- print "<h2>MySQL: Group by clause in PHP</h2>";
- $result = mysql_query("select id, avg(salary)as totalsal from emp_dtl group by id"); // Second query
- echo "<table border='1'>
- <tr>
- <th>EmpId</th>
- <th>Salary</th>
- </tr>";
- while($row = mysql_fetch_array($result))
- {
- echo "<tr>";
- echo "<td>" . $row['id'] . "</td>";
- echo "<td>" . $row['totalsal'] . "</td>";
- echo "</tr>";
- }
- echo "</table>";
- print "<h2>MySQL: Group by with having clause</h2>";
- $result = mysql_query("select id, count(*) as total from emp_dtl group by id having count(*)>1"); // Third query
- echo "<table border='1'>
- <tr>
- <th>EmpId</th>
- <th>Duplicate Records</th>;
- </tr>";
- while($row = mysql_fetch_array($result))
- {
- echo "<tr>";
- echo "<td>" . $row['id'] . "</td>";
- echo "<td>" . $row['total'] . "</td>";
- echo "</tr>";
- }
- mysql_close($con);
- ?>
- echo "</table>";
Note: In the above example, first the query "select * from emp_dtl" simply shows all the information of the emp_dtl table. And the second query "select id, avg (salary) as totalsal from emp_dtl group by id" is grouped by the id column data and the result is each group's average total salary. And the third "query select id, count(*) as total from emp_dtl group by id having count(*)>1" counts the number of duplicate records.


Kesavan KrishnanPosted Jun 28, 2017, 3:01 AM
This is not a problem with group by and having (The main problem with input data).How data is duplicated in the table i mean 102?