2

我需要找到一种方法来计算住在同一所房子里并投票“DEMO”、“REP”或“DEMO-REP”的选民人数。到目前为止,我已经得到了这个,http://sqlfiddle.com/# !3/469d4/3

例如,miles 和 Raquel 住在同一所房子里,并且都投了“REP”,他们将被计入“REP”列。Chris 和 Tania 都住在同一所房子里,并且投票了“REP”和“DEMO”,所以他们将进入“DEMO-REP”列。小提琴结果需要。

1 http://img824.imageshack.us/img824/3305/resultbx.png

提前致谢

4

2 回答 2

0

我认为这可以满足您的要求:

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

在这里,我假设“地址”是家庭的代理,因为数据中没有家庭字段。

于 2012-07-23T16:20:59.750 回答
0

编辑:这适用于您的 SQL Fiddle 代码。

我会这样做:

SELECT COUNT(Voted) AS TOTAL, 
(
SELECT COUNT(DISTINCT address) FROM test4
WHERE address NOT IN (SELECT address FROM test4 WHERE Voted = 'REP')
) AS Demo, 
(SELECT COUNT(DISTINCT address) FROM test4
WHERE address NOT IN (SELECT address FROM test4 WHERE Voted = 'DEMO')
) AS Rep,
(SELECT COUNT(DISTINCT address) FROM test4
WHERE address IN (SELECT address FROM test4 WHERE Voted = 'REP') AND address IN (SELECT address FROM test4 WHERE Voted = 'DEMO')
) AS DemoRep
  FROM test4
于 2012-07-23T16:38:30.357 回答