我想知道如何根据其约束来计算某个值的百分比
例如,假设我有一个名为 Cats 的假设表。我将以下值插入其中:
Create table Cats (Cat_ID int, Cat_name varchar(max), Cat_Hometown varchar(max), Gender varchar(max), Birth_Year int);
INSERT INTO Cats (Cat_ID, Cat_Name, Cat_Hometown, Gender, Birth_year)
VALUES (1, 'Blue','Boston','M', 1980),
(2, 'Steamer','Plymouth','F', 1999),
(3, 'Stack','Newton','F', 1980),
(4, 'Overflow','Boston','M', 1978),
(5, 'CatorDog','Allston','F', 1999);
如果我想确定 1980 年出生在领先家乡的母猫的百分比怎么办?我似乎无法弄清楚。 我所说的领先家乡是指最普通的家乡。
最佳答案
假设领先的家乡意味着给定年份表中的行数最多,您可以按计数排序并获得最常见的行。然后使用条件聚合来获取百分比。 AVG(gender='F')
使用 MySQL 将条件视为 bool 值的事实,返回 1 表示 True,0 表示 False。
select AVG(gender='F')
from cats
where birth_year=1980 and
cat_hometown in (select cat_hometown
from cats
where birth_year=1980
group by cat_hometown
order by count(*) desc
limit 1)
关于mysql - 在sql中,如何根据列中的约束来计算列中值的百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44423011/