查询计算符合两个单独条件的人员

时间:2012-07-23 16:13:13

标签: sql sql-server-2008 common-table-expression

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

例如,里程和拉克尔住在同一栋房子里并且都投了“REP”,他们将被计入“REP”栏。克里斯和塔尼亚都住在同一所房子里并投票“REP”和“DEMO”,所以他们将进入'DEMO-REP'专栏。 小提琴的结果必须是。

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

提前致谢

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:0)

编辑:这适用于您的SQL小提琴代码。

我愿意:

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