关于oracle中分类查询的问题现在有4个分类,比如就称为1:超市,2:医院,3:学校,4:酒店, 想统计每个分类的个数
关于oracle中分类查询的问题
现在有4个分类,比如就称为1:超市,2:医院,3:学校,4:酒店,
想统计每个分类的个数,
比如表是这样的:
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
[其他解释]
可以加个表 记录4个类型 方便很多 不然就构造表
[其他解释]
现在有字典表,存储这四个类型的
[其他解释]
需要按顺序排列的话 分组加个c1,按c1排序即可
group by c1,c2
order by c1
[其他解释]
嗯,如果我的类型存在一个字典表里,比如叫tcDicType,
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
