[英]How do I calculate the percentage of a value in a column based on constraints on it , in sql?
我想知道如何根據對它的約束來計算某個值的百分比
例如,假設我有一個名為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年出生在主要家鄉的母貓所占的百分比怎么辦? 我似乎無法弄清楚。 領導家鄉,我的意思是最普通的家鄉。
假設領先的家鄉意味着給定年份中表中的行數最多,則可以order by
計數進行order by
並獲得最常見的行。 然后使用條件聚合獲得百分比。 AVG(gender='F')
使用以下事實:MySQL將條件視為布爾值,對於True返回1,對於False返回0。
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)
您需要找出最常見的家鄉。 這有點挑戰,但是子查詢會有所幫助。 所以:
select avg(c.Gender = 'Female' and c.Birth_Year = 1980 and c.Cat_Hometown = ch.Cat_Hometown)
from cats c cross join
(select c2.Cat_Hometown
from cats c2
group by c2.Cat_Hometown
order by count(*) desc
limit 1
) ch;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.