以下几列中都有普查数据:
FIRST_NAME,SURNAME,职业,HOUSEHOLD_ID,DISTRICT,COUNTY
以及一些示例数据:
Anne, Boyle, Student, 7090989, Green Acres, Coolidge
John, Boyle, Farmer, 7090989, Green Acres, Coolidge
Mary, Boyle, Farmer's wife, 7090989, Green Acres, Coolidge
James, Egan, Carpenter, 1090933, Green Acres, Coolidge
Margret, Egan, Teacher, 1090933, Green Acres, Coolidge
William, Dunne, Merchant, 2090921, Falls, Cleveland
Anne, Smyth, Widow, 1110166, Range, Cleveland
Daniel, McCann, Farm labourer, 1011112, Griffin, Cleveland
Timothy, McCann, Farm labourer, 1011112, Griffin, Cleveland
Patrick, Sullivan, Farmer, 2217733, Ards, Cleveland
Maggie, Sullivan, Farmer, 2217733, Ards, Cleveland
Michael, Petterson, Farmer labourer, 2227229, Ards, Cleveland
因此,我希望计算每个地区的农户数量。每个家庭都有唯一的ID,而一个农户则定义为至少有一个居住者LIKE "%Farm%"
的家庭。因此,家庭中的农民人数与是否至少有一位农民无关。对于上面的数据,我应该得到以下结果:
Green Acres, Coolidge, 1
Griffin, Cleveland, 1
Ards, Cleveland, 2
这是我确定每个地区的农民人数的方式:
Select DISTRICT, COUNTY, COUNT(*) from census where OCCUPATION like "%Farm%" group by DISTRICT, COUNTY;
要获取每个地区的家庭人数,我会这样做:
select DISTRICT, COUNTY, COUNT(distinct(HOUSEHOLD_ID)) from census group by DISTRICT, COUNTY;
那我该如何计算每个地区的农户数。
更新
A county is made up of uniquely named districts.
答案 0 :(得分:1)
我如何计算每个地区的农户数量
这意味着按DISTRICT
分组:
select DISTRICT,
count(distinct HOUSEHOLD_ID) counter
from census
where OCCUPATION like 'Farm%'
group by DISTRICT;
如果您还想要COUNTY
列:
select
COUNTY,
DISTRICT,
count(distinct HOUSEHOLD_ID) from census
where OCCUPATION like 'Farm%'
group by COUNTY, DISTRICT
请参见demo
答案 1 :(得分:0)
尝试此查询
SELECT a.DISTRICT,
a.COUNTY,
COUNT(*)
FROM (
SELECT DISTINCT(b.HOUSEHOLD_ID),
b.DISTRICT,
b.COUNTY FROM census b
WHERE b.OCCUPATION like '%FARM%'
) as a
GROUP BY
a.DISTRICT,
a.COUNTY