从多列中获取MySQL的百分比

时间:2017-03-19 14:47:34

标签: mysql sql database

我有一张表:

schoolId | string1 | string2
   1     |  yes    | no
   1     |  no     | yes
   1     |  null   | yes
   1     |  yes    | no

我试图获得如下结果表:

value | string1 | string2
yes   |   50%   |  50%
no    |   25%   |  50%
null  |   25%   |  0%

到目前为止,我已经把这个放在一起了:

select (table.string1/string1_sum)*100 as 'string1 %'
from table , (SELECT SUM(string1) string1_sum FROM table) as t
where schoolId = 4

2 个答案:

答案 0 :(得分:0)

以下查询将为string1和string2中的每个值提供counttotal

SELECT a.value, 
(SELECT count(*) FROM school WHERE ifnull(string1, 'null') = a.value AND schoolid = 1) AS s1,
(SELECT count(*) FROM school WHERE ifnull(string2, 'null') = a.value AND schoolid = 1) AS s2,
(SELECT count(*) FROM school WHERE schoolid = 1) AS total
FROM
(SELECT DISTINCT IFNULL(string1, 'null') AS value FROM school WHERE schoolid = 1
UNION
SELECT DISTINCT IFNULL(string2, 'null') AS value FROM school WHERE schoolid = 1) a

根据这些值,您可以在应用程序中计算percentage

这是 SQL Fiddle

<强>更新

要计算查询本身的计数,您可以将上述查询包装到另一个查询中并执行除法:

SELECT b.value, (b.s1/b.total)*100 AS string1, (b.s2/b.total)*100 AS string2
FROM (
SELECT a.value, 
(SELECT count(*) FROM school WHERE ifnull(string1, 'null') = a.value AND schoolid = 1) AS s1,
(SELECT count(*) FROM school WHERE ifnull(string2, 'null') = a.value AND schoolid = 1) AS s2,
(SELECT count(*) FROM school WHERE schoolid = 1) AS total
FROM
(SELECT DISTINCT IFNULL(string1, 'null') AS value FROM school WHERE schoolid = 1
UNION
SELECT DISTINCT IFNULL(string2, 'null') AS value FROM school WHERE schoolid = 1) a
) b

以下是更新的 SQL Fiddle

答案 1 :(得分:0)

嗯。您可以获得基本计数:

select value, sum(string1), sum(string2)
from ((select string1 as value, 1 as string1, 0 as string2
       from t
      ) union all
      (select string2 as value, 0 as string1, 1 as string2
       from t
      )
     ) t
group by value;

您可以通过加入以下内容获得整体计数:

select value, sum(string1) / tt.cnt, sum(string2) / tt.cnt
from ((select string1 as value, 1 as string1, 0 as string2
       from t 
      ) union all
      (select string2 as value, 0 as string1, 1 as string2
       from t
      )
     ) t cross join
     (select count(*) as cnt from t) tt
group by value;

注意:这会将“百分比”计算为比率(这就是我喜欢看它们的方式)。您可以根据需要格式化结果。