Both of the previous suggestions misses out empid #5.--prepare test datadeclare @t table (empid tinyint, mgrid tinyint)insert @tselect 1, 1 union allselect 2, 1 union allselect 3, 2 union allselect 4, 3 union allselect 5, 4-- do the work-- Query 1select distinct e1.empid, isnull(e2.cnt, 0) cntfrom @t e1left join ( select mgrid, count(*) cnt from @t group by mgrid ) e2 on e2.mgrid = e1.empid-- Query 2select distinct e1.empid, (select count(*) from @t e2 where e2.mgrid = e1.empid) cntfrom @t e1-- Query 3select e1.empid, sum(case when e2.mgrid is null then 0 else 1 end) cntfrom @t e1left join @t e2 on e2.mgrid = e1.empidgroup by e1.empid-- Query 4select id, count(*) - 1 cntfrom ( select mgrid id from @t union all select empid from @t ) qgroup by id
Peter LarssonHelsingborg, Sweden