8

我的问题是关于百分比的,我不是专家,所以我会尝试以更好的方式解释。

我的 mysql 服务器中有一个表,比如 700 条记录,类似这样

+-------+---------+----------+-------+
| Name  | country | language | Birth |
+-------+---------+----------+-------+
| Lucy  | UK      | EN       | 1980  |
| Mari  | Canada  | FR       | 1990  |
| Gary  | Canada  | EN       | 1982  |
| Stacy | Jamaica | EN       | 1986  |
| Joao  | Brasil  | PT       | 1984  |
+-------+---------+----------+-------+

因此,我查询了 1980 年到 1985 年之间的所有记录,结果将是:

+------+---------+----------+-------+
| Name | country | language | Birth |
+------+---------+----------+-------+
| Lucy | UK      | EN       | 1980  |
| Gary | Canada  | EN       | 1982  |
| Joao | Brasil  | PT       | 1984  |
+------+---------+----------+-------+

从这个结果我想获得:

  1. 那些年之间每种语言出现的百分比

    EN = 75% (3 is the total in this case)
    PT = 25%
    
  2. 结果表中出现的每个国家/地区的百分比

    UK = 33%
    Canada = 33%
    Brasil = 33%
    

我的意思是如何将结果转换为变量以在最终函数中使用它们。

4

2 回答 2

1

这可能有效,但大致如下:

set @total_rows = (SELECT COUNT(*) FROM table WHERE Birth between 1980 and 1985);

SELECT language, percentage
FROM (
    SELECT language, concat(count(language)/@total_rows, "%") AS percentage 
    FROM table WHERE Birth between 1980 and 1985
)
于 2012-10-04T14:02:27.373 回答
0

我会在这里回答,因为在评论中做 SQL 不太舒服。

要获得百分比,您只需将先前的输出作为视图并添加百分比列,应该这样做:

select NAME, QUANTITY, QUANTITY/(select count(1) from TABLE) as PERCENTAGE
from (
    select NAME, count(1) as QUANTITY
    from TABLE
    where condition
    group by NAME
)

但这并没有真正优化,因为您每次想要获取单行时都会调用整个表的计数,即使 MySQL 将索引计数结果,它仍然不是最好的。

您应该做的是首先将表格的总大小放入您的 php 中:

select count(1) as totalsize
from TABLE

然后在您的下一个请求中使用它:

select NAME, QUANTITY, QUANTITY/[totalsize from php] as PERCENTAGE
from (
    select NAME, count(1) as QUANTITY
    from TABLE
    where condition
    group by NAME
)
于 2012-10-12T05:23:25.747 回答