34,590
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据:#1
if object_id('tempdb.dbo.#1') is not null drop table #1
create table #1(物品名 varchar(8), 数量 int)
insert into #1
select '毛巾', 10 union all
select '床单', 21 union all
select '枕巾', 2 union all
select '毛巾', 13 union all
select '毛巾', 5 union all
select '枕巾', 3
--> 测试数据:#2
if object_id('tempdb.dbo.#2') is not null drop table #2
create table #2(物品名 varchar(8), 数量 int)
insert into #2
select '床单', 2 union all
select '枕巾', 1 union all
select '枕巾', 1
select 物品名, sum(数量)数量
from
(
select * from #1
union all
select 物品名, -数量 from #2
) t
group by 物品名
/*
物品名 数量
-------- -----------
床单 19
毛巾 28
枕巾 3
*/
select 物品名,
sum(数量)数量
from
(
select 物品名,数量 from 表1
union all
select 物品名,-数量 from 表1
)t
group by 物品名