有两个表:a(part,qty,date),b(part,name,on_hand,)
select  a.part,
b.name,
b.category,
b.total_on_hand,
sum(a.qty >= 0) as qty1,
        sum(a.qty < 0) as qty2,
        (select sum(qty)
        from a
        where a.part = b.part
        and date between(2008/02/03,2008/03/24)) as total,
        b.total_on_hand - total as on_hand,
        on_hand + qty1 + qty2 as last_on_hand
from    a,b
where   a.part =b_part
and     b.date between(2008/01/03,2008/02/03)
group by a.part,
 b.name,
 b.category,
 b.total_on_hand
order by a.part;
其中a表的qty有可能是正的,也可能是负的。qty1时正的相加(求增加量),qty2时负的相加(求减少量)。
问题1:qty1 和 qty2 要怎么求。
问题2:我这个sql文对吗?有可以改进的吗?
注意的是:between里的时间是不一样的。
问题3: select sum(qty)
       from a
       where a.part = b.part
       and date between(2008/02/03,2008/03/24)) as total 是要当成一个字段的,这样表达对吗。

解决方案 »

  1.   

    MRP ?
    == 思想重于技巧 ==
      

  2.   

    问题1:qty1 和 qty2 要怎么求。 sum(IF(a.qty >= 0,a.qty,0)) as qty1,
    sum(IF(a.qty < 0,a.qty,0)) as qty2,
    == 思想重于技巧 ==
      

  3.   

    问题2:我这个sql文对吗?有可以改进的吗?
    太复杂了,一眼看不明白,建议直接到mysql中执行一下,
    由于在select 段中包含了subquery,所以应该可以改进, 换成 join
    == 思想重于技巧 ==
      

  4.   

    问题3到mysql一试即知,好像要看不同版本的
    == 思想重于技巧 ==
      

  5.   

    1、LS 的方法。
    2、用CASE WHEN