我认为这可以满足您的要求:
select sum(votes) as total, sum(demo*(1-rep)) as demoonly,
sum(rep*(1-demo)) as reponly, sum(demo*rep) as demorep
from (select address, cont(*) as votes,
max(case when voted = 'DEMO' then 1 else 0 end) as demo,
max(case when voted = 'REP' then 1 else 0 end) as rep
from t
group by address
) t
假设您想要一个以上的家庭(地址):
select sum(votes) as total, sum(demo*(1-rep)) as demoonly,
sum(rep*(1-demo)) as reponly, sum(demo*rep) as demorep
from (select address, count(*) as votes,
max(case when voted = 'DEMO' then 1 else 0 end) as demo,
max(case when voted = 'REP' then 1 else 0 end) as rep
from test4
group by address
having count(distinct name) > 1
) t
在这里,我假设“地址”是家庭的代理,因为数据中没有家庭字段。