日期:2014-05-18  浏览次数:20530 次

三个表的一个计算难住了.高手帮忙
三个表
1.工资表 a表
km je
1 5
2 10
3 15
4 20
2.物资表 b表
bh lx(0,1)
3.使用表 c表
bh sl(+,-)

需求:
b表的lx为0时,c表的sl为+就把ABC(sl)*a表km为1的je
b表的lx为0时,c表的sl为-就把ABC(sl)*a表km为2的je
b表的lx为1时,c表的sl为+就把ABC(sl)*a表km为3的je
b表的lx为1时,c表的sl为-就把ABC(sl)*a表km为4的je
b.bh=c.bh

联合语句写条件,把这个使用过的物质金额算出来.



------解决方案--------------------
把表的结构和结果贴好点。这样看不明白
------解决方案--------------------
这么复杂 0 0
------解决方案--------------------
SQL code

--> 测试数据: @a表
declare @a表 table (km int,je int)
insert into @a表
select 1,5 union all
select 2,10 union all
select 3,15 union all
select 4,20

--> 测试数据: @b表
declare @b表 table (bh int,lx int)
insert into @b表
select 1,0 union all
select 2,1 union all
select 3,1 union all
select 4,0 union all
select 5,1

--> 测试数据: @c表
declare @c表 table (bh int,sl varchar(2))
insert into @c表
select 1,'+' union all
select 2,'-' union all
select 3,'+' union all
select 4,'-' union all
select 5,'-'

select c.*,b.lx,
case when c.sl='+' and b.lx=0 then (select je from @a表 where km=1)
when c.sl='-' and b.lx=0 then (select je from @a表 where km=2)
when c.sl='+' and b.lx=1 then (select je from @a表 where km=3)
when c.sl='-' and b.lx=1 then (select je from @a表 where km=4)
end as je
from @c表 c left join @b表 b on c.bh=b.bh

/*
bh          sl   lx          je
----------- ---- ----------- -----------
1           +    0           5
2           -    1           20
3           +    1           15
4           -    0           10
5           -    1           20
*/