现在有4个分类,比如就称为1:超市,2:医院,3:学校,4:酒店,
想统计每个分类的个数,
比如表是这样的:
ID name type
1 希望小学 3
2 人们医院 2 统计每个分类的个数,如果在表中没有就个数就为0,结果最好是这样:
TypeName NUM
超市 0
医院 1
学校 1
酒店 0
怎么用sql写啊?
想统计每个分类的个数,
比如表是这样的:
ID name type
1 希望小学 3
2 人们医院 2 统计每个分类的个数,如果在表中没有就个数就为0,结果最好是这样:
TypeName NUM
超市 0
医院 1
学校 1
酒店 0
怎么用sql写啊?
with t1 as
(
select 1 c1,'超市' c2 from dual
union all
select 2 c1,'医院' c2 from dual
union all
select 3 c1,'学校' c2 from dual
union all
select 4 c1,'酒店' c2 from dual
),t2 as
(
select 1 id,'希望小学' name,3 type from dual
union all
select 2 id,'人们医院' name,2 type from dual
)select c2,count(id) c_num
from t1 left join t2 on t1.c1 = t2.type
group by c2
c2 c_num
---------------------
1 酒店 0
2 学校 1
3 医院 1
4 超市 0
order by c1
id name
1 超市
2 医院
3 学校
4 酒店
这样怎么查呢?
select a.name,count(b.id) c_num
from tcDicType a left join 表2 b on a.id = b.type
group by a.id,a.name
order by a.id