select 库房, 商品编码 , 商品名称,sum(数量),单价=(case sum(数量) when 0 then 单价 else avg(单价)end),进货日期 from 表  group by 库房, 商品编码 , 商品名称,进货日期
没测试,不知道好用不

解决方案 »

  1.   

    给你提供思路,不想去写语句,自己动手^_^
    1.按商行、库房分组
    2.求和数量,单价
    3.判断单价为零时,查找该产品的最近一次记录求值。(select * from 表名 where 日期=(select max(date) where 商品名='xx' and 库房='xx'))
      

  2.   

    select 库房, 商品编码 , 商品名称,sum(数量),单价=(case sum(数量) when 0 then 单价 else avg(单价)end),进货日期 from 表  group by 库房, 商品编码 , 商品名称,进货日期
      

  3.   

    select  库房 ,商品编码,商品名称,数量=sum(数量),
    单价=(case  when  sum(数量)= 0  then 
                                     (select  单价 from test b  where   商品名称=a.商品名称 and 库房=a.库房 and 进货日期=(select max(进货日期) from test  where 商品名称=b.商品名称 and 库房= b.库房)) 
     else round(sum(数量*单价)/sum(数量),2) end),
    max(进货日期)
    from  test a
    group by  库房,商品编码,商品名称
      

  4.   

    select  库房 ,商品编码,商品名称,数量=sum(数量),
    单价=(case  when  sum(数量)= 0  then 
                                     (select  单价 from test b  where   商品名称=a.商品名称 and 库房=a.库房 and 进货日期=(select max(进货日期) from test  where 商品名称=b.商品名称 and 库房= b.库房)) 
     else round(sum(数量*单价)/sum(数量),2) end),
    进货日期=max(进货日期)
    from  test a
    group by  库房,商品编码,商品名称--结果
    库房   商品编码    商品名称   数量     单价      进货日期  
    ---- --------------- ---- -------------   -------- ----------- -----------------------------
    A1   12501-12501   aaa              0            13.0          2001-05-16 00:00:00.000
    A1   13000-             BBB           8            13.13         2001-08-15 00:00:00.000
    A2   12501-12501   aaa              1            15.0           2001-08-12 00:00:00.000(3 row(s) affected)