gpt4 book ai didi

php - MySQL/PHP : group by classes

转载 作者:行者123 更新时间:2023-11-29 06:41:27 25 4
gpt4 key购买 nike

我有一个包含百分比(值 0-100)的表(假设表名称=TableA 只有 1 个名为百分比的列)。

我想做的是在类中划分百分比。例如,假设类宽度 = 2。我的最终结果是:

percent | quantity
------------------
[0-2) | 5
[2-4) | 43
... | ...
[96-98) | 232
[98-100]| 173

我想过一些方法来做这件事,但我需要一个高效的方法,考虑到该表包含大约 500.000 行。最后我将在 php 中创建一个图表,所以我真的不在乎解决方案是基于 mysql 还是基于 php。

1)(嗯,这肯定不是最佳选择,但我写它是为了弄清楚我在问什么)

select count (*) from tableA where percent>=0 and percent<2;
select count (*) from tableA where percent>=2 and percent<4;
...

2) 使用php读取每一行并对其进行分类

select * from tableA
<?php while ($row=...)
$class[intval($row[0]/50)]++; ?>

3) 创建表 TableB 如下:

floor | roof
------------
0 | 2
2 | 4
4 | 6
... | ...

然后

select tableB.floor/2,count(*) 
from tableA join tableB
on tableA.percent>=tableB.floor and tableA.percent<tableB.roof
group by tableB.floor/2

我更喜欢第二个,虽然我不确定是使用php还是使用mysql进行计算更好。

你有什么更好的想法吗?

最佳答案

您可以使用公式创建直方图桶,而无需第二个表的帮助。

SELECT count(*), FLOOR(percent/2)*2 percent
FROM tableA
GROUP BY FLOOR(percent/2)*2
ORDER BY FLOOR(percent/2)*2

这应该是非常有效的,尤其是当您碰巧在 percent 列上有一个索引时。

例如,percent 值 18 和 19 将通过 GROUP BY 公式转换为 18。

关于php - MySQL/PHP : group by classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21331784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com