从另一个表的表中选择计数

时间:2013-12-05 12:34:27

标签: sql sql-server sql-server-2008

我有两个与person_id相关的表(main_table)和(sub_table)..现在我想从主表中选择person_id和sub_table中与main_table相关的记录数,其中sub_table中的记录不等于'eco'..现在问题是当我做这个..查询得到的person_id不等于'eco'...但我想从查询中选择每个person_id并选择count 0如果sub_table中的person_id等于'eco':

    SELECT m.person_id, COUNT(*) AS eco FROM  (SELECT person_id FROM Main_table
                    WHERE     (person_id ='c')AS m INNER JOIN
                      (SELECT  person_id
                         FROM         sub_table
                         WHERE person_status != 'eco' 
                         GROUP BY person_id) AS eco ON eco.person_id = m.person_id GROUP BY m.person_id

2 个答案:

答案 0 :(得分:1)

SELECT m.person_id, 
       countNonEco = (SELECT COUNT(*) FROM sub_table s
                      WHERE m.person_id = s.person_id
                      AND (s.person_status IS NULL OR s.person_status <> 'eco'))
FROM Main_table m

答案 1 :(得分:1)

问题在于您INNER加入了您的sub_table,因此根据定义,您只能将结果限制为此表中的条目不等于eco的人。

我认为你可以通过简单地离开加入你的子表来做到这一点,在连接标准中使用person_status:

SELECT  m.Person_ID,
        COUNT(s.Person_ID) AS NonEcoCount
FROM    Main_Table m
        LEFT JOIN sub_table s
            ON s.Person_ID = m.Person_ID
            AND s.person_status != 'eco'
GROUP BY m.Person_ID;