mysql, 如何查询分组后 每组的总条数

现在有这样的需求: 根据某一个条件进行分组统计,显示分组后每组的总条数。


数据表:
物品表(wuPin)  :id,name,types,units   (自增,物品名称,物品类型,管理单位)


 

案件表(anJian) :id,name,types,units   (自增,案件名称,案件类型,管理单位)

 

 

查询条件:根据“管理单位”统计其下有多少贵重物品、危险物品、刑事案件、治安案件。

最后要的结果如下:




 

 

请问高手们,sql 怎么写??????

 

以上表格都是我直接在数据新建的,方便大家看,实际不是这些表,也更多。
 

SELECT sum(DECODE(a.types,'贵重物品',1,0)) AS 贵重物品,
sum(DECODE(a.types,'危险物品',1,0)) AS 危险物品,
sum(DECODE(a.types,'刑事案件',1,0)) AS 刑事案件,
sum(DECODE(a.types,'治安案件',1,0)) AS 治安案件,
a.units AS 管理单位
FROM (SELECT * FROM anJian UNION ALL SELECT * FROM wupin) a
GROUP BY units ;测试了一下跟你要的结果是一样的,用了decode函数,应该还有其他方法,这个可以参考哈。

统计需要行列转换,写了个比较粗糙的,你可以再简化下,功能肯定是实现了:
select a.贵重物品,a.危险物品,b.刑事案件,b.治安案件,b.units as 管理单位 from (
select
sum(decode(temp1.types,'贵重物品',temp1.c,0))贵重物品,
sum(decode(temp1.types,'危险物品',temp1.c,0))危险物品,
temp1.units
from (select count(0)c,types,units from wuPin a group by a.types,a.units)temp1
group by temp1.units
)a,
(
select
sum(decode(temp2.types,'刑事案件',temp2.c,0))刑事案件,
sum(decode(temp2.types,'治安案件',temp2.c,0))治安案件,
temp2.units
from (select count(0)c,types,units from anJian a group by a.types,a.units)temp2
group by temp2.units)b
where a.units=b.units

典型的纵表转化成横表,只写了第一个表,第二个表类似,然后把2各表连接下就行了
sql仅供参考
select
m.危险物品, n.贵重物品, m.治安单位
from
(select
b.name as '危险物品', b.units as '治安单位'
from
(select
count(w.name) as name, w.types, w.units
from
wupin w
group by w.units , w.types
having w.types = '危险物品') b) m
left join
(select
c.name as '贵重物品', c.units as '治安单位'
from
(select
count(w.name) as name, w.types, w.units
from
wupin w
group by w.units , w.types
having w.types = '贵重物品') c) n ON m.治安单位 = n.治安单位

count(*) where types=?

select count(*) from wuPin group by types