简体   繁体   中英

mysql query to count and sum

i have a table where same data is appearing again and again the table structure is like below.id is autoincrement.pm is for userid.it will appear again and again like beliw table.i want to display the output as the extract of entire table in descending order. suppose the table consists of 100 rows and the userid 15 comes 10 times which is highest then it should come at the top then the other id which is coming next like that . i tried but not working here is my code as well

id    userid
1      33
2      34
3      37
4      33 
5      33
6      37

the output i want is

     userid   nos
      33       3
      37       2
      34       1

please guide . i tried with this code

$res = sql_query("select count(userid) as total from tableA");

echo'<table>';
while ($row = sql_fetch_array($res)) {
echo ' <tr><td>'.$row['userid'].'</td></tr></table>';

You need to use a GROUP BY statement

SELECT userid, COUNT(userid) AS nos FROM tableA
    GROUP BY userid ORDER BY nos DESC;
SELECT userid, COUNT(userid) FROM tableA AS nos GROUP BY userid ORDER BY nos DESC

Then you can access:

$row['userid'] for the user ID

$row['nos'] for the count

Your looping methodology is wrong.

$res = sql_query("select userid, count(userid) as total from tableA group by userid order by total desc");
echo'<table>';
while ($row = sql_fetch_array($res)) {
  echo ' <tr><td>'.$row['userid'].'</td><td>'.$row['total'].'</td></tr>';
}
echo '</table>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM