三个表
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联合语句写条件,把这个使用过的物质金额算出来.

解决方案 »

  1.   

    b表的lx只有0,1两种类型,c表的sl用正(+)负(-)来保存
      

  2.   


    --> 测试数据: @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
    */
    按你的要求改一下即可。
      

  3.   

    嗯.我一直用case想在条件上做限制,你这个思路,很明白了.还想要用SUM来合计起来.好像SUM不能用于子查询,在看看.谢谢了.
      

  4.   

    用case 无法sum了.所以只好去写个存储过程了.5楼的方法很值得学习.