34,593
社区成员
发帖
与我相关
我的任务
分享
--测试数据
if not object_id(N'Tempdb..#T1') is null
drop table #T1
Go
Create table #T1([id] int,[name] nvarchar(23),[code] int,[size] int)
Insert #T1
select 1,N'物品1',1001,20 union all
select 2,N'物品2',1002,40
GO
if not object_id(N'Tempdb..#T2') is null
drop table #T2
Go
Create table #T2([id] int,[pid] int,[num] int)
Insert #T2
select 1,1,20 union all
select 2,1,30 union all
select 3,2,10
GO
if not object_id(N'Tempdb..#T3') is null
drop table #T3
Go
Create table #T3([id] int,[code] int,[num] int)
Insert #T3
select 1,1001,10 union all
select 2,1002,20 union all
select 3,1002,30
Go
--测试数据结束
SELECT #T1.name,
t2.num AS 入库数量,
t3.num AS 出库数量
FROM #T1
LEFT JOIN
(SELECT pid, SUM(num) AS num FROM #T2 GROUP BY pid) t2
ON t2.pid = #T1.id
LEFT JOIN
(SELECT code, SUM(num) AS num FROM #T3 GROUP BY code) t3
ON t3.code = #T1.code;