Mysql count frequency(Mysql计数频率)
问题描述
我检查过类似的问题,但对我的确切问题没有帮助.
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
等等.
我需要计算年龄的频率:
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]}]);";
}
?>
目标是构建图表
推荐答案
你需要按共同年龄对行进行分组,然后计算每组中有多少行:
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
然后将其转换为数组,请在 PHP 中执行此操作:
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];
}
您现在有一个名为 $frequencies 的关联数组,其中年龄为键,频率为值.
You now have an associative array called $frequencies with the ages as keys and their frequency as values.
这篇关于Mysql计数频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mysql计数频率


基础教程推荐
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01