Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql count frequency

I've checked similar questions but it didnt help in my precise question.

So, my table goes like this:

id age
1  30
2  36
3  30
4  52
5  52
6  30
7  36

etc..

I need to count the frequency of ages:

age freq
30   2
36   3
52   2

How can I grab this freq? After this I will need to work with that data, so it might be necessary using array? Thanks!

function drawChart() {

      // Create the data table.

      var data = new google.visualization.DataTable();
      data.addColumn('string', 'age');
      data.addColumn('number', 'freq');

        <?php
            while($row = mysql_fetch_row($result)) 
            {
            $frequencies[$row[0]] = $frequencies[1];
            echo "data.addRow(['{$row[0]}', {$row[1]}]);";
            }

        ?>

The goal is build a chart

like image 231
noneJavaScript Avatar asked Nov 15 '12 13:11

noneJavaScript


Video Answer


2 Answers

You need to group the rows by the common age, then count how many are in each group:

SELECT age, COUNT(*) AS freq FROM ages GROUP BY age

To then convert it into an array, do this in PHP:

$frequencies = array ();
$result = mysql_query('SELECT age, COUNT(*) AS freq FROM table GROUP BY age');
if($result === false) { handle error here... }
while($row = mysql_fetch_row($result)) {
    $frequencies[$row[0]] = $row[1];
}

You now have an associative array called $frequencies with the ages as keys and their frequency as values.

like image 167
Nicholas Shanks Avatar answered Sep 29 '22 14:09

Nicholas Shanks


select age, name, count(*) freq from user_age group by age

Sqlfiddle : http://sqlfiddle.com/#!2/266d5/2

like image 26
Avin Varghese Avatar answered Sep 29 '22 14:09

Avin Varghese