我有一个大型数据集,我想知道如何计算某个属性值的最常见事件。
例如,假设我有一个名为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年为女性猫确定最常见的城市怎么办?我该怎么办?我似乎无法绕过它。
答案 0 :(得分:2)
您可以尝试以下查询来执行此操作。
select Cat_Hometown, count(Cat_Hometown) as Cats_Count from Cats where gender='F' and Birth_year=1980 group by Cat_Hometown order by count(Cat_Hometown) desc limit 1;
:)
答案 1 :(得分:0)
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);
;with cat_count as (
select count(1) NumberofCats, Cat_Hometown from #Cats
where Gender = 'F'
and Birth_year = 1980
group by cat_hometown
)
select Cat_Hometown from cat_count
where NumberofCats = (select max(numberofcats) from cat_count)