要在左外连接中计算两个值到同一个表

时间:2013-12-17 19:56:11

标签: sql-server-2008

(family_table)相关的两个表(children_table)family_id, 如何通过一个查询来计算拥有state 'a'的孩子和每个家庭state 'b'的孩子?

我尝试了查询,但是children_state 'b'的计数结果和children_state 'a'的计数错误,我不知道问题出在哪里,我的查询是:

select f.family_id ,
count(c.family_id) as [B children Count] ,
count(cp.family_id) as [A children Count]
FROM Family_table as f left outer join children_table as c
on c.family_id = f.family_id and c.children_state = 'B' left outer join children_table as cp
on cp.family_id = f.family_id and c.children_state = 'A'

2 个答案:

答案 0 :(得分:1)

这应该做你想要的:

select f.family_id ,
       SUM(CASE c.children_state WHEN 'B' THEN 1 ELSE 0 END) as [B children Count] ,
       SUM(CASE c.children_state WHEN 'A' THEN 1 ELSE 0 END) as [A children Count]
       SUM(CASE WHEN c.children_state <> 'd' and c.children_state <> 'e' THEN 1 ELSE 0 END) AS [Some other count]
FROM Family_table as f 
join children_table as c
on c.family_id = f.family_id
GROUP BY f.family_id

它通过使用和来工作,然后在该总和中应用您感兴趣的条件用于特定计数。这样,您可以从一个连接中获得多个不同的“计数”

如果您有其他条件,则只需使用不同的CASE语句添加其他SUM列

答案 1 :(得分:0)

尝试分组

下面的sql未经验证,因为我无法访问sqlserver

select f.family_id , c.children_state, count(c.children_state) 
FROM Family_table as f left outer join children_table as c 
on c.family_id = f.family_id 
and c.children_state in ('A','B')
group by f.family_id , c.children_state