日期:2014-05-17 浏览次数:20684 次
WITH I AS
(
SELECT GoodsId,SUM(Quantity) Quantity
FROM DetailIn
), O AS
(
SELECT GoodsId,SUM(Quantity) Quantity
FROM DetailOut
)
SELECT G.*,ISNULL(I.Quantity,0) dInQty,ISNULL(O.Quantity,0) dOutQty,ISNULL(I.Quantity,0)-ISNULL(O.Quantity,0) dLeftQty
FROM Goods G LEFT JOIN I ON G.ID=I.GoodsId
LEFT JOIN O ON G.ID=O.GoodsId
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-09-30 10:54:42
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
-- Jun 10 2013 20:09:10
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------
--> 测试数据:[Goods]
if object_id('[Goods]') is not null drop table [Goods]
go
create table [Goods]([字段ID] varchar(4),[Name] varchar(6))
insert [Goods]
select 'A001','B2铅笔'
--> 测试数据:[DetailIn]
if object_id('[DetailIn]') is not null drop table [DetailIn]
go
create table [DetailIn]([字段ID] int,[GoodsId] varchar(4),[Quantity] int)
insert [DetailIn]
select 1,'A001',100 union all
select 2,'A001',200 union all
select 3,'A001',500
--> 测试数据:[DetailOut]
if object_id('[DetailOut]') is not null drop table [DetailOut]
go
create table [DetailOut]([字段ID] int,[GoodsId] varchar(4),[Quantity] int)
insert [DetailOut]
select 1,'A001',400 union all
select 2,'A001',80
--------------开始查询--------------------------
select a.*,[DetailIn].[Quantity],[DetailOut].[Quantity]
from [Goods] a LEFT JOIN (SELECT goodsid,SUM([Quantity])[Quantity] FROM [DetailIn] GROUP BY goodsid)[DetailIn] ON a.[字段ID]=[DetailIn].goodsid
LEFT JOIN (SELECT goodsid,SUM([Q