有一张表,有如下字段和数据单位编码, 发生类型,发生金额
1   存入     5000
1         存入     1000
2         存入     5000
1         取出     8000
我想用SQl算出每个单位存入的金额取出的金额,还有结余(每个单位的存入数-取出数)数怎样写?
以下是存入和取出的,怎样算存结的
select 单位编码,
存入基金=isnull(sum(case 发生类型 when '存入' then 发生金额 end),0),
取出资金=isnull(sum(case 发生类型 when '取出' then 发生金额 end),0)

解决方案 »

  1.   

    有一张表,有如下字段和数据单位编码,   发生类型,   发生金额
    1      存入       5000
    1            存入       1000
    2            存入       5000
    1           取出        8000
    我想用SQl算出每个单位存入的金额取出的金额,还有结余(每个单位的存入数-取出数)数怎样写?
    以下是存入和取出的,怎样算存结的
    select 单位编码,
    存入基金=isnull(sum(case 发生类型 when '存入' then 发生金额 end),0),
    取出资金=isnull(sum(case 发生类型 when '取出' then 发生金额 end),0)
      

  2.   

    select 
        单位编码,
        存入基金=isnull(sum(case 发生类型 when '存入' then 发生金额 end),0),
        取出资金=isnull(sum(case 发生类型 when '取出' then 发生金额 end),0),
        结余=isnull(sum(case 发生类型 when '存入' then 发生金额 when '取出' then -发生金额 end))
    from
        表
    group by 
        单位编码