读书人

求两表求和的SQL语句解决方法

发布时间: 2012-03-05 11:54:01 作者: rapoo

求两表求和的SQL语句
有两张表Table1,Table2。table1数据如下:
ID product amount
----------------------------------
1 A 10
2 A 12
3 B 5
4 B 11
5 A 3


table2数据如下:
ID product amount
----------------------------------
1 A 5
2 A 10
3 B 5


我想求出table1中A、B的总数,再减去table2中A、B的总数,然后生成新表
ID product amount
----------------------------------
1 A 10
2 A 11

这个SQL怎么写?

[解决办法]
select a.product,(a.amount -b.amount ) from
(select product,sum(amount) amount from table1 group by product)a
(select product,sum(amount) amount from table2 group by product)b
where a.product=b.product

读书人网 >SQL Server

热点推荐