一个表结构如下:
name    jg    zl
米      200   买
衣      300   买
裤      100   买
米      150   卖
裤      50    卖
米     200    买
...
要求查询结果如下:
米    250
裤    50即按name分类,和zl的进出,合计现在还有多少数量并且数量要小于280
谢谢大家!

解决方案 »

  1.   

    用case sum 两个函数,应该就可以搞定啊
      

  2.   

    select * from
    (select name,sum((case when zl='买' then 1 else -1 end)*jg) as jg from 表 group by name )a
    where (jg<280)
      

  3.   

    select name,sum(case when zl='买' then jg when zl='卖' then -jg else 0 end) as jg from table group by name  having jg<280
      

  4.   

    to 楼上的,直接having是不可以的 select name,sum((case when zl='买' then 1 else -1 end)*jg) as jg from 表 group by name 
    having sum((case when zl='买' then 1 else -1 end)*jg)<280这样还不如字表