gpt4 book ai didi

mysql - 从 MySQL 获取多列百分比

转载 作者:行者123 更新时间:2023-11-29 19:13:32 24 4
gpt4 key购买 nike

我有一个像这样的表:

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

最佳答案

以下查询将为您提供 string1 和 string2 中每个值的计数总计:

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

根据这些值,您可以计算应用程序中的百分比

这是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

关于mysql - 从 MySQL 获取多列百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42887945/

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