数据汇总问题
我有表product和表stock 
 表Product: 
 pid                                    quantity    
 001                                       1 
 002                                       2 
 001                                       2 
 003                                       5   
 表stock: 
 sid                        pid                     squantity 
 1                              001                           3 
 2                              004                           2 
 3                              002                           2   
 想得到如下结果: 
 pid            sum(quantity)      sum(squantity)               sum(quantity)-sum(squantity) 
 001                           3                                             3                                                         0 
 002                           2                                             2                                                         0 
 003                           5                                             0                                                         5 
 004                           0                                             2                                                         -2   
 谢谢指点.
------解决方案--------------------select isnull(m.pid,n.pid) pid , isnull(m.quantity ,0) quantity , isnull(n.squantity , 0) squantity , isnull(m.quantity ,0) - isnull(n.squantity , 0) from 
 ( 
   select pid ,sum(quantity) quantity from Product group by pid 
 ) m 
 full join 
 ( 
   select pid ,sum(squantity) squantity from stock group by pid 
 ) n 
 on m.pid = n.pid 
------解决方案--------------------Select 
 	IsNull(A.pid, B.pid) As pid, 
 	IsNull(A.quantity, 0) As quantity, 
 	IsNull(B.squantity, 0) As squantity, 
 	IsNull(A.quantity, 0) - IsNull(B.squantity, 0) As [quantity - squantity] 
 From 
 	(Select pid, SUM(quantity) As quantity From Product Group By pid) A 
 Full Join 
 	(Select pid, SUM(squantity) As squantity From stock Group By pid) B 
 On A.pid = B.pid
------解决方案--------------------if object_id( 'pubs..Product ') is not null