select
    a.id,
    qty=a.qty-isnull(b.qty,0)
from (select id,sum(qty) qty from tableB group by id) a
 left join (select id,sum(qty) qty from tableA group by id) b
   on a.id=b.id
where a.qty-b.qty<>0

解决方案 »

  1.   

    select 
      id,
      a.qty-b.qty as qty
    from
     (select id,sum(qty) as qty from A group by id) a,
     (select id,sum(qty) as qty from B group by id) b
    where
     a.id=b.id
    and 
     a.qty-b.qty<>0
      

  2.   

    if object_id('tablea')is not null
       drop table tablea
    go
    create table tablea([id] int,[qty] int)
    insert tablea select 1,4
    insert tablea select 1,7
    insert tablea select 1,29
    insert tablea select 2,12
    insert tablea select 2,15
    insert tablea select 3,14
    go
    if object_id('tableb')is not null
       drop table tableb
    go
    create table tableb([id] int,[qty] int)
    insert tableb select 1,8
    insert tableb select 1,7
    insert tableb select 1,15
    insert tableb select 2,13
    insert tableb select 2,14
    insert tableb select 3,17
    go
    select
        a.id,
        qty=a.qty-isnull(b.qty,0)
    from (select id,sum(qty) qty from tableB group by id) a
     left join (select id,sum(qty) qty from tableA group by id) b
       on a.id=b.id
    where a.qty-b.qty<>0
    /*
    id          qty
    ----------- -----------
    1           -10
    3           3(2 行受影响)
    */
      

  3.   

    select   id,  a.qty-b.qty as qty
    from
     (select id,sum(qty) as qty from A group by id) a,
     (select id,sum(qty) as qty from B group by id) b
    where a.id=b.id and  a.qty-b.qty<>0
      

  4.   

    select a.ID,sum(sumqtya-sumqtyb) from (
    select ID,sum(qty) as sumqtya from tablea group by ID) a,
    (select ID,sum(qty) as sumqtyb from tableb group by ID) b
    where a.ID = b.ID
    group by a.ID
    having sum(sumqtya-sumqtyb) <> 0
      

  5.   

    select A.id,(sum(B.qty) - sum(A.qty))/sqrt(COUNT(A.id)) as qty from A 
    left join B on A.id = B.id
    group by A.id having sum(B.qty) - sum(A.qty) <> 0
      

  6.   

    select A.id,(sum(B.qty) - sum(A.qty))/sqrt(COUNT(A.id)) as qty from A 
    left join B on A.id = B.id
    group by A.id having sum(B.qty) - sum(A.qty) <> 0