日期:2014-05-17  浏览次数:20516 次

求这么一个SQL语句 或是存储过程,谢谢。
有两表,如下

表2pId对应表1的id 表2 liyou列只会有三种值 :报废、丢失、其他 
我现在的意思是 根据表1的gzTime 比如从2006/12/2 到 2008/6/1 这段时间内的 表peizhi的shuliang合计,
加上
表2的对应的isUse为1的合计,
表2的对应的isUse为1的合计
表2的对应的isUse为0的,liyou为“报废”的合计,
表2的对应的isUse为0的,liyou为“丢失”的合计,
表2的对应的isUse为0的,liyou为“其他”的合计

求这么一个SQL语句 或是存储过程,谢谢。

------解决方案--------------------
SQL code
--构建测试数据
create table peizhi(id int, pihao char(4), gzTime datetime, shuliang int)
insert into peizhi
select 1, '0602', '2006/2/1' ,5 union all 
select 2, '0603', '2006/12/2', 4 union all 
select 3, '0701', '2007/1/3' ,3 union all
select 4, '0702', '2007/5/4' ,2 union all
select 5, '0801', '2008/6/1' ,5 
create table zhuji(id int, pId int, isUse bit, liyou varchar(10)) 
insert into zhuji
select 1, 1, 0, '报废' union all select 
2, 1, 0, '报废' union all select 
3, 1, 0, '报废' union all select 
4, 1, 0, '报废' union all select 
5, 2, 0, '报废' union all select 
6, 2, 0, '报废' union all select 
7, 2, 0, '报废' union all select 
8, 2, 0, '报废' union all select 
9, 3, 1, '' union all select 
10, 3, 0, '丢失' union all select 
11, 3, 1, '' union all select 
12, 4, 1, '' union all select 
13, 4, 0, '其他' union all select 
14, 5, 1, '' union all select 
15, 5, 1, '' union all select 
16, 5, 0, '丢失' union all select 
17, 5, 1, '' union all select 
18, 5, 1,'' 

--解决方案
select sum(shuliang) 合计, '未使用' 类别 from  peizhi a,zhuji b where a.id = b.id and isUse = 0
union all
select isnull(sum(shuliang),0) 合计, '使用中' from  peizhi a,zhuji b where a.id = b.id and isUse = 1 
union all
select sum(shuliang) 合计, liyou from  peizhi a,zhuji b 
where a.id = b.id and isUse = 0 and (gzTime between '2006/12/2' and '2008/6/1') group by liyou
/*
合计          类别
----------- ----------
19          未使用
0           使用中
14          报废

(3 行受影响)


*/