多表查询在联接的问题,求解
现已写了三个多表查询,分别是关于采购、入库、出库的 ,
关于采购的:selete1查询结果:
年份 月份 物料代码 物料名称 采购重量
关于入库的:selete2查询结果:
年份 月份 物料代码 物料名称 入库重量
关于出库的:selete3查询结果:
年份 月份 物料代码 物料名称 出库重量
现在需要接这三个表联全在一起,,比如我要查找2012年物料代码为10001的物料,则显示1-12个月的采购、入库、出库的重量(上面的查询已经计算好)的记录
年份 月份 物料代码 采购重量 入库重量 出库重量
2012 1 10001 1000 500 600
2012 2 10001 0 200 600
比如2月此物料没有采购,但是1月有采购记录,在2月份入库,则显示1月采购数量为0。。
请教这个最终的查询如果整合上面三个查询呢?
[最优解释]
0 字段值 ,你单独运行其中的一个 就明白了 。
[其他解释]
SELECT S1.年份 ,
M.number AS 月份 ,
S1.物料代码 , --這個地方不是很嚴謹,假設的是有採購的話,肯定會就在入庫或出庫的範圍
ISNULL(S1.采购重量, 0) AS 采购重量 ,
ISNULL(S2.入库重量, 0) AS 入库重量 ,
ISNULL(S3.出库重量, 0) AS 出库重量
FROM master..spt_values M
LEFT JOIN selete1 S1 ON M.number = S1.月份
LEFT JOIN selete2 S2 ON M.number = S2.月份
AND S1.年份 = S2.年份
LEFT JOIN selete3 S3 ON M.number = S3.月份
AND S1.年份 = S3.年份
WHERE m.type = 'P'
AND m.number BETWEEN 1 AND 12
AND S1.年份 = 2012
---1、采购的查询
select YEAR(copurchase.PurDate) AS NF,MONTH(copurchase.PurDate) AS YF,
pbMaterial.MaterialID AS WLDM,pbMaterial.MaterialName AS WLName,SUM(coPurchaseDetail.Amount) AS BZSL
from copurchase
inner join coPurchaseDetail on copurchase.PurNo=coPurchaseDetail.PurNo
inner join pbMaterial on coPurchaseDetail.MaterialNo=pbMaterial.MaterialNo
where YEAR(copurchase.PurDate)=2012 and MONTH(copurchase.PurDate)=9
GROUP BY YEAR(PurDate),MONTH(PurDate) ,pbMaterial.MaterialID,pbMaterial.MaterialName
----2、入库的查询
select YEAR(stInStore.InDate) AS NF,MONTH(stInStore.InDate) AS YF, pbMaterial.MaterialID AS WLDM,
pbMaterial.MaterialName AS WLName,SUM(stInStoreDetail.OriginalWeight) AS RKZL
from stInStore
inner join stInStoreDetail on stInStore.InStoreNo=stInStoreDetail.InStoreNo
inner join coPurchaseDetail on coPurchaseDetail.DetailNo=stInStoreDetail.PurDetailNo
inner join pbMaterial on coPurchaseDetail.MaterialNo=pbMaterial.MaterialNo
where YEAR(stInStore.InDate)=2012 and MONTH(stInStore.InDate)=9 and stInStore.TypeNo=3
group by YEAR(stInStore.InDate),MONTH(stInStore.InDate),pbMaterial.MaterialID,pbMaterial.MaterialName
---3、出库的查询
select YEAR(stOutStore.OutDate) AS NF,MONTH(stOutStore.OutDate) AS YF,pbMaterial.MaterialID AS WLDM,
pbMaterial.MaterialName AS WLName,SUM(stOutStoreDetail.OriginalWeight) AS CKZL
from stOutStore
inner join stOutStoreDetail on stOutStore.OutStoreNo=stOutStoreDetail.OutStoreNo
inner join pmOrderMaterial on pmOrderMaterial.OrderMaterialNo=stOutStoreDetail.OrderMaterialNo
inner join pbMaterial on pbMaterial.MaterialNo=pmOrderMaterial.MaterialNo
where YEAR(stOutStore.OutDate)=2012 and MONTH(stOutStore.OutDate)=9 and stOutStore.TypeNo in (3,33,9,12)
group by YEAR(stOutStore.OutDate),MONTH(stOutStore.OutDate),pbMaterial.MaterialID,pbMaterial.MaterialName