由於我的問題有點特別,我還沒有找到答案,並經過很長時間的搜索後,所以在這裏:我有兩個表:In_Stock和Out_Stock。我用下面的選擇:
從SQL中的兩個不同表中刪除
IN_STOCK:
select
INs.CatID as CategoryID,
INs.SubCatID as SubcategoryID, Sum(INs.Quantity) as QuantityIN
from IN_Stock INs
group by INs.CatID, INs.SubCatID
╔════════════╦═══════════════╦════════════╗
║ CategoryID ║ SubcategoryID ║ QuantityIN ║
╠════════════╬═══════════════╬════════════╣
║ 2 ║ 9 ║ 0 ║
║ 1 ║ 16 ║ 8 ║
║ 1 ║ 27 ║ 5 ║
║ 1 ║ 30 ║ 160 ║
║ 1 ║ 31 ║ 6 ║
║ 1 ║ 39 ║ 35 ║
║ 1 ║ 40 ║ 7 ║
║ 2 ║ 44 ║ 13 ║
║ 2 ║ 54 ║ 6 ║
║ 2 ║ 70 ║ 5 ║
║ 3 ║ 87 ║ 3,5 ║
╚════════════╩═══════════════╩════════════╝
OUT_Stock:
select
OUTs.CatID as CategoryID,
OUTs.SubCatID as SubcategoryID,
Sum(OUTs.Quantity) as QuantityOUT
from OUT_Stock OUTs
group by OUTs.CatID, OUTs.SubCatID
╔════════════╦═══════════════╦═════════════╗
║ CategoryID ║ SubcategoryID ║ QuantityOUT ║
╠════════════╬═══════════════╬═════════════╣
║ 1 ║ 30 ║ 30 ║
║ 1 ║ 39 ║ 15 ║
╚════════════╩═══════════════╩═════════════╝
我得到的是這個表波紋管(這顯然不是正確的)。
select
INs.CatID as CategoryID,
INs.SubCatID as SubcategoryID,
Sum(INs.Quantity) as QuantityIN,
SUM(OUTs.Quantity) as QuantityOUT,
SUM(INs.Quantity)- SUM(OUTs.Quantity) as RemainingQuantity
from IN_Stock INs
left join OUT_Stock OUTs on INs.CatID=OUTs.CatID and INs.SubCatid=OUTs.SubCatid
group by INs.catid, INs.subcatid
╔════════════╦═══════════════╦═════════════╦════════════╦═══════════════════╗
║ CategoryID ║ SubcategoryID ║ QuantityIN ║ QuantityOUT║ RemainingQuantity ║
╠════════════╬═══════════════╬═════════════╬════════════╬═══════════════════╣
║ 2 ║ 9 ║ 0 ║ ║ ║
║ 1 ║ 16 ║ 8 ║ ║ ║
║ 1 ║ 27 ║ 5 ║ ║ ║
║ 1 ║ 30 ║ 320 ║ 150 ║ 170 ║
║ 1 ║ 31 ║ 6 ║ ║ ║
║ 1 ║ 39 ║ 35 ║ 30 ║ 5 ║
║ 1 ║ 40 ║ 7 ║ ║ ║
║ 2 ║ 44 ║ 13 ║ ║ ║
║ 2 ║ 54 ║ 6 ║ ║ ║
║ 2 ║ 70 ║ 5 ║ ║ ║
║ 3 ║ 87 ║ 3,5 ║ ║ ║
╚════════════╩═══════════════╩═════════════╩════════════╩═══════════════════╝
我想要的是使SQL返回類似表波紋管一個選擇......我想知道是否和如何我可以在RemaningStock collumn看到:其中SubCategoryID = 30和其中SubCategoryID = 39。
╔════════════╦═══════════════╦════════════╦════════════╦═══════════════════╗
║ CategoryID ║ SubcategoryID ║ QuantityIN ║ QuantityIN ║ RemainingQuantity ║
╠════════════╬═══════════════╬════════════╬════════════╬═══════════════════╣
║ 2 ║ 9 ║ 0 ║ ║ ║
║ 1 ║ 16 ║ 8 ║ ║ ║
║ 1 ║ 27 ║ 5 ║ ║ ║
║ 1 ║ 30 ║ 160 ║ 30 ║ 130 ║
║ 1 ║ 31 ║ 6 ║ ║ ║
║ 1 ║ 39 ║ 35 ║ 15 ║ 20 ║
║ 1 ║ 40 ║ 7 ║ ║ ║
║ 2 ║ 44 ║ 13 ║ ║ ║
║ 2 ║ 54 ║ 6 ║ ║ ║
║ 2 ║ 70 ║ 5 ║ ║ ║
║ 3 ║ 87 ║ 3,5 ║ ║ ║
╚════════════╩═══════════════╩════════════╩════════════╩═══════════════════╝
兩個表有一個或多個記錄某一類別或子類別
任何幫助深表感謝。非常感謝!
SQL或Access VBA代碼對我來說都很好。
PS:由於這是我的第一篇文章,請「溫柔」。
+1該表的格式! – Brad 2013-02-18 15:16:30