select 商品编号=code,上期结存=sum(case when date<'2002-10-12' then amount*type else 0 end),
本期收入=sum(case when date>='2002-10-12' and date<='2002-10-13' and type=1 then amount else 0 end),
本期发出=sum(case when date>='2002-10-12' and date<='2002-10-13' and type=-1 then -amount else 0 end),
本期结存=sum(type*amount)
from 库存跟综表
where date<='2002-10-13' 
group by code

解决方案 »

  1.   

    用自定义函数:
    create function GetReport(
        @dt1 datetime,
        @dt2 datetime)
    returns table 
    as
    return(
    select 商品编号=code,上期结存=sum(case when [date]<@dt1 then amount*type else 0 end),
    本期收入=sum(case when [date]>=@dt1 and [date]<=@dt2 and type=1 then amount else 0 end),
    本期发出=sum(case when [date]>=@dt1 and [date]<=@dt2 and type=-1 then -amount else 0 end),
    本期结存=sum(type*amount)
    from 库存跟综表
    where [date]<=@dt2 
    group by code
    )
    go
    调用:
    select * from dbo.GetReport('2002-10-12','2002-10-13')
      

  2.   

    是否可以做成视图,使用联合试图解决呢。我试了很多次也没有Finish。
      

  3.   

    Haiwer(海阔天空) 够厉害,有机会多请教
      

  4.   

    可以考虑使用存储过程啊,两个输入参数为你的时间段的StartDateTime,
    EndDateTime,
    结合Haiwer(海阔天空)的应该时很容易完成的。