先group by 再order by

解决方案 »

  1.   

    select * 
    from 
       (select a,b,sum(c) ,sum(d) as ad
        from 
        (
            select a,b,c,d
            from table1,table2
            union 
            select a,b,c,d
            from table1,table3
        )
        group by a,b)
    where ac<>0 or ad <>0
    order by a
      

  2.   

    select a,b,sum(c) as ac,sum(d) as ad
         from 
          (
           select a,b,c,d
           from table1,table2
           union 
           select a,b,c,d
           from table1,table3
        )
          where ac<>0 or ad <>0
          group by a,b
          order by a
      

  3.   

    select a,b,sum(c) as ac,sum(d) as ad
         from 
          (
           select a,b,c,d
           from table1,table2    --为什么没有条件
           union 
           select a,b,c,d
           from table1,table3  --为什么没有条件    )
         group by a,b
         Having sum(c)<>0 or sum(d)<>0
      

  4.   

    select a,b,sum(c) as ac,sum(d) as ad
         from 
          (
           select a,b,c,d
           from table1,table2
           union 
           select a,b,c,d
           from table1,table3
        ) temp
          where temp.ac<>0 or temp.ad <>0
          group by temp.a,temp.b
          order by temp.a
      

  5.   

    呵呵,没注意ac,ad 是聚集函数算出来的。
    select a,b,sum(c) as ac,sum(d) as ad
         from 
          (
           select a,b,c,d
           from table1,table2
           union 
           select a,b,c,d
           from table1,table3
        )
          where ac<>0 or ad <>0
          group by a,b
          having sum(c)<>0 or sum(d)<>0 
          order by a
      

  6.   

    少删了点,这个:
    select a,b,sum(c) as ac,sum(d) as ad
         from 
          (
           select a,b,c,d
           from table1,table2
           union 
           select a,b,c,d
           from table1,table3
        )
          group by a,b
          having sum(c)<>0 or sum(d)<>0 
          order by a