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

解决方案 »

  1.   

    with datamodle do
       begin
         close;
         sql.clear;
         sql.add('select 米,衣,裤 from 表名 where (米=300) or (衣=300) or (裤=50)
         open; 
        end;
      

  2.   

    select name,sum(case when zl='买' then jg when zl='卖' then -jg else 0 end) total from table group by name
    未经测试,就是用case区分zl来决定jg的正负。
      

  3.   

    --建立测试环境
    Create Table 表(name varchar(10),jg varchar(10),zl varchar(10))
    --插入数据
    insert into 表
    select '米','200','买' union all
    select '衣','300','买' union all
    select '裤','100','买' union all
    select '米','100','卖' union all
    select '裤','50','卖' union all
    select '米','200','买'--测试语句
     select name,sum((case when zl='买' then 1 else -1 end)*jg) as jg from 表 group by name 
     
    --删除测试环境
    Drop Table 表
    /*---查询结果
    name       jg          
    ---------- ----------- 
    裤          50
    米          300
    衣          300--*/
      

  4.   

    select distinct a.name ,( select sum(jg) from table where zl='买'  and name=a.name) -( select sum(jg) from table where zl='卖'  and name=a.name)  as jg from table a
      

  5.   

    select distinct a.name ,( select sum(jg) from table where zl='买'  and name=a.name group by a.name) -( select sum(jg) from table where zl='卖'  and name=a.name group by a.name)  as jg from table a group by a.name
      

  6.   

    给你推荐zj的新书,或许可以给你许多帮助
    http://www.dearbook.com.cn/subject/renyouSQL/