各位大哥,又有了一个新问题。请出手相助啊~下面我列出了表t1和表t2的数据
t1表
id    number  class_id
06       2       596
74       4       597
74       1       598
74       6       599
74       13      600
77       10      601
90       8       602
t2表
id    number   class_id
06       2        596
74       4        597
74       1        598
74       2        599
74       3        599
90       3        602
90       5        602
要得到如下结果,该如何写sql?(t1表是一个库存表,t2表是已经使用表,现在要查询出:t1-t2 =剩余的。)
id    number   class_id
74       1        599
74       13       600
77       10       601

解决方案 »

  1.   

    select  
        a.id,a.number-isnull(b.number,0) as number,a.class_id
    from 
        t1 a
    left join
        (select id,sum(number) as number,class_id from t2 group by id,class_id) b
    on
        a.id=b.id and a.class_id=b.class_id
    where
        a.number-isnull(b.number,0)>0
      

  2.   

    declare @t1 table(id varchar(6),number int,class_id int)
    insert into @t1 select '06',2 ,596
    insert into @t1 select '74',4 ,597
    insert into @t1 select '74',1 ,598
    insert into @t1 select '74',6 ,599
    insert into @t1 select '74',13,600
    insert into @t1 select '77',10,601
    insert into @t1 select '90',8 ,602
    declare @t2 table(id varchar(6),number int,class_id int)
    insert into @t2 select '06',2,596
    insert into @t2 select '74',4,597
    insert into @t2 select '74',1,598
    insert into @t2 select '74',2,599
    insert into @t2 select '74',3,599
    insert into @t2 select '90',3,602
    insert into @t2 select '90',5,602
    select  
        a.id,a.number-isnull(b.number,0) as number,a.class_id
    from 
        @t1 a
    left join
        (select id,sum(number) as number,class_id from @t2 group by id,class_id) b
    on
        a.id=b.id and a.class_id=b.class_id
    where
        a.number-isnull(b.number,0)>0/*
    id     number      class_id    
    ------ ----------- ----------- 
    74     1           599
    74     13          600
    77     10          601
    */
      

  3.   

    select  
        id,sum(number) as number,class_id
    from 
        (
        select 
            id,number,class_id 
        from 
            t1
        union all
        select 
            id,-number,class_id 
        from 
            t2
        ) as t
    group by 
        id,class_id
    having
        sum(number)>0