select count(*) as num from orders o where o.aid = 'a03'; select o.cid, count(*) as numOfOrders from orders o where o.aid = 'a03' group by o.cid order by cid; select count(distinct o.cid) as num from orders o where o.aid = 'a03'; select c.cid, (select count(*) from orders o where o.aid = 'a03' and c.cid = o.cid ) as num from customers c order by c.cid; select cid, case when numOfOrders is null then 0 else numOfOrders end as num from (select o.cid, count(*) as numOfOrders from orders o where o.aid = 'a03' group by o.cid) right outer join customers using(cid) order by cid; select c.cid, 0 as num from customers c where not exists (select * from orders o where o.aid = 'a03' and o.cid=c.cid); select o.cid, count(*) as num from orders o where o.aid = 'a03' group by o.cid union select c.cid, 0 as num from customers c where not exists (select * from orders o where o.aid = 'a03' and o.cid=c.cid);