请问 子查询中能用分组函数么?
我想实现:查询汇总信息如下
业务编码 国编码 录入总数(吨),录入总数(头)
004       123    130             140
003       sss    240             400就是汇总信息。上面这些 录入总数(吨)和录入总数(头)是同一个业务编码下面的汇总信息
业务上有个要求:数据库isAgree字段表示状态。不等于0表示两种状态(通过,待审核。isAgree -1,0,1 分别表示待审核,未通过,通过。)
也就是说汇总的数据是两种状态的总和。但是业务同时又要求 如果一个业务编码下面的所有的记录(一个业务编码下面有多个记录)的状态都是通过 即isAgree=1。那么这个业务就不显示。哎呀呀说的有点乱了:
  这样的 比如004在数据库中有很多条记录都是004 他们不同只是状态(有些通过了,有些待审核...),录入的数据。
  现在就是来汇总编码为004的所有数据。如果数据库004的状态都是通过的话就不汇总了。只要其中有一个004的状态是待审 
  核,那么就汇总所有004 的数据。
我写的sql如下:
select osi.plancode ,osi.gctcode ,(select sum(osi1.productnumber) from  chukudantable osi1 where osi.plantype=2 and osi.isAgree!=0  group by osi.plancode ),(select sum(osi1.tounumber) from  chukudantable osi1 where osi.plantype=2 and osi.isAgree!=0  group by osi.plancode ) from chukudantable osi where osi.plantype=2 and osi.isAgree=-1 and osi.inuse=0  group by osi.plancode
在子查询中我用了分组。我预期结果是:
004       123    130             140
003       sss    240             400
但是上面的语句报错
于是我把子查询中的 group by osi.plancode 去掉。
结果却是:
004       123    370            540
003       sss    370            540
请问正确sql该怎么写啊

解决方案 »

  1.   

    可以肯定的是你这个子查询明显是错的。报的错应该是什么:返回多条记录之类的。就是说你的主SQL的一条记录,要求只查询中只有一个对应的记录。
    你先试试这个
    select osi.plancode,
           osi.gctcode,
           (select sum(osi1.productnumber)
              from chukudantable osi1
             where osi.plantype = 2
               and osi.isAgree != 0 osi1.plancode = osi.plancode),
           (select sum(osi1.tounumber)
              from chukudantable osi1
             where osi.plantype = 2
               and osi.isAgree != 0 osi1.plancode = osi.plancode)
      from chukudantable osi
     where osi.plantype = 2
       and osi.isAgree = -1
       and osi.inuse = 0
     group by osi.plancode
      

  2.   

    哦,两个条件之前少个and,
    osi.isAgree != 0 and  osi1.plancode = osi.plancode
      

  3.   

    osi1.plancode = osi.plancode??不大看得懂啊 求解释
      

  4.   

    for example
    select osi.plancode,
           osi.gctcode,
           sum(case isAgree when 0 else osi.productnumber end),
           sum(case isAgree when 0 else osi1.tounumber end)
      from chukudantable osi
     where osi.plantype = 2
       and osi.inuse = 0
       and not exists (select 1 from chukudantable 
                       where plancode = osi.plancode
                         and isAgree = 0) --存在isAgree为0的不显示,也就是不选取
     group by osi.plancode
      

  5.   

    select osi.plancode,
           osi.gctcode,
           sum(case isAgree when 0 then 0 else osi.productnumber end),
           sum(case isAgree when 0 then 0 else osi1.tounumber end)
      from chukudantable osi
     where osi.plantype = 2
       and osi.inuse = 0
       and isAgree != 0 --看错了,LZ是全为1才不显示
     group by osi.plancode