Mysql Counting Frequency

I checked similar questions, but that did not help in my exact question.

So my table is as follows:

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

etc..

I need to calculate the frequency of ages:

 age freq 30 2 36 3 52 2 

How can I capture this frequency? After that, I will need to work with this data, so it may be necessary to use an 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 to build a chart

+4
source share
4 answers

You need to group the strings by total age, and then calculate how many of them are in each group:

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

To convert it to an array, do it 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 $ frequency, with age as keys and their frequency as values.

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

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

+1
source
 select age, count(*) freq from mytable group by age 
0
source
 select age, count(id) as freq from table group by age 
0
source

Source: https://habr.com/ru/post/1446227/


All Articles