SQL语句分类汇总查询,急!感兴趣的进来看看!

来源:百度知道 编辑:UC知道 时间:2024/06/07 13:44:05
一个药品明细表Medic_Detail,统计出当前库存量(当前数量=入库数量-出库数量-报损数量)
有以下字段:
药品编码 数量 出入库标识(0入库,1出库,2报损)
medicid num type
1 100 0
2 100 0
3 100 0
1 10 1
2 10 1
1 3 2
3 5 2
要求统计为以下结果:
药品编码 当前库存
1 83
2 90
3 95

在MS SQL2005中测试通过

--1.生成测试数据
select 1 as medicid, 100 as num, 0 as type into tmp_Test
union all select 2, 100, 0
union all select 3, 100, 0
union all select 1, 10 ,1
union all select 2, 10 ,1
union all select 1, 3, 2
union all select 3, 5, 2

--2.分类汇总
select medicid,sum(case when [type]=0 then num else -1*num end)
from tmp_test
group by medicid

--3.结果
1 87 --该条你的结果是错的,100-10-3=87
2 90
3 95

自联接两次即可:
select a.medicid as 药品编码, a.num-b.num-c.num as 当前库存
from Medic_Detail a join Medic_Detail b on a.type=0 and b.type=1 and a.medicid=b.medicid join Medic_Detail c on a.type=0 and c.type=2 and a.medicid=c.medicid
---------------------------------
为了避免有库存而没有出库与报损,造成查询结果为空的情况,修改一下:
select a.medicid as 药品编码, a.num-isnull(b.num,0)-isnull(c.num,0) as 当前库存
from Medic_Detail a left join Medic_Detail b on a.type=0 and b.type=1 and a.medicid=b.medicid left join Med