我正在尝试运行MySQL查询并使用PHP执行以下操作:
我需要将列中的数据分组(GROUP BY),然后计算(COUNT)每个组中的行数。之后,我需要将给定组中的行数除以组的数量,以获得该组的受欢迎程度。
所以如果我有一张包含以下数据的表:
Version_Number
1.1
1.2
1.1
1.2
1.2
1.1
I need the final output to be:
1.1 50%
1.2 50%
答案 0 :(得分:1)
你可能需要为mysql调整这个(我通常在oracle中工作),但是:
SELECT
( count(*) / totalCount * 100) AS percentOfVersionedThings
, Version_Number
FROM tableOfVersionedThings
INNER JOIN ( SELECT count(*) as totalCount FROM tableOfVersionedThings ) ON 1=1
GROUP BY Version_Number
如果这是Oracle,我建议使用分析,但我不确定MySQL中是否存在等价物。也就是说,在您的情况下,一个简单的子查询应该可以解决问题,它应该适用于任何SQL数据库。
答案 1 :(得分:1)
这是我在尝试上述操作后最终做的事情:
$result = mysql_query("SELECT COUNT(*) AS nsites FROM table WHERE auth = '$auth'") or
die(mysql_error());
$return_sites = mysql_fetch_array($result);
if (!$return_sites['nsites']) {
echo "...";
} else {
$esult = mysql_query("SELECT * FROM table WHERE auth = '$auth' GROUP BY theme_version") or die(mysql_error());
while($row = mysql_fetch_array($esult)){
$get_current_version = $row['theme_version'];
$vresult = mysql_query("SELECT COUNT(*) AS nversion FROM table WHERE auth = '$auth' AND theme_version = '$get_current_version'") or die(mysql_error());
$version = mysql_fetch_array($vresult);
$percent = round($version['nversion'] / $return_sites['nsites'] * 100);
echo "...";
}
}
答案 2 :(得分:0)
这样的事情:
select v."Version_Number", count(v."Version_Number"),count(v."Version_Number")::float / (select count(v2."Version_Number")::float from versions v2 )::float * 100::float
from versions as v
group by v."Version_Number"