表一(AAA)
商品名称MC 商品总量SL
A 100
B 120
表二(BBB)
商品名称MC 出库数量SL
A 10
A 20
B 10
B 20
B 30
用一条SQL语句算出商品A,B目前还剩多少商品?
商品名称MC 商品总量SL
A 100
B 120
表二(BBB)
商品名称MC 出库数量SL
A 10
A 20
B 10
B 20
B 30
用一条SQL语句算出商品A,B目前还剩多少商品?
调试欢乐多
from AAA a,BBB b
where a.mc=b.mc
group by a.mc
--> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
--> 测试数据:表一
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'表一')
AND type in (N'U'))
DROP TABLE 表一
GO---->建表
create table 表一([商品名称MC] varchar(1),[商品总量SL] int)
insert 表一
select 'A',100 union all
select 'B',120
GO
--> 数据库版本:
--> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
--> 测试数据:表二
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'表二')
AND type in (N'U'))
DROP TABLE 表二
GO---->建表
create table 表二([商品名称MC] varchar(1),[出库数量SL] int)
insert 表二
select 'A',10 union all
select 'A',20 union all
select 'B',10 union all
select 'B',20 union all
select 'B',30
GO--> 查询结果
SELECT a.商品名称MC,a.商品总量SL,余量 =a.商品总量SL - SUM(b.出库数量SL)
FROM 表一 a join 表二 b
on a.商品名称MC = b.商品名称MC
group by a.商品名称MC,a.商品总量SL
--> 删除表格
--DROP TABLE 表一
--> 查询结果
SELECT * FROM 表二
--> 删除表格
--DROP TABLE 表二
from AAA mc
if object_id('[AAA]') is not null drop table [AAA]
go
create table [AAA] (MC varchar(1),SL int)
insert into [AAA]
select 'A',100 union all
select 'B',120
--> 测试数据: [BBB]
if object_id('[BBB]') is not null drop table [BBB]
go
create table [BBB] (MC varchar(1),SL int)
insert into [BBB]
select 'A',10 union all
select 'A',20 union all
select 'B',10 union all
select 'B',20 union all
select 'B',30 select a.mc, a.sl-b.sl
from AAA a,
(select mc,sl=sum(sl) from BBB group by mc)b
where a.mc=b.mc
mc
---- -----------
A 70
B 60(2 行受影响)
create table aaa(mc char(8),sl int)
insert into aaa
select 'a',100 union all
select 'b',120
create table bbb(mc char(8),sl int)
insert into bbb
select 'a',10 union all
select 'a',20 union all
select 'b',10 union all
select 'b',20 union all
select 'b',30select a.mc 商品名称,a.sl-sum(b.sl)余量
from aaa as a,bbb as b where a.mc=b.mc
group by a.mc,a.sl商品名称 余量
-------- -----------
a 70
b 60(所影响的行数为 2 行)
from AAA a,BBB b
where a.mc=b.mc
group by a.mc