我有两个主键和外键表(MaterialId)
MaterialId MaterialName OpeningStock 1 Pen 100 2 Pencil 50
MaterialId PurchaseQty SalesQty Date 1 500 0 2016-12-15 1 0 0 2016-12-16 1 300 0 2016-12-17 1 0 400 2016-12-18 1 0 0 2016-12-19 1 0 0 2016-12-20 1 0 400 2016-12-21 1 200 100 2016-12-22
现在当我通过@FromDate和@Todate时 我想输出如下:
Date MaterialName OpeningStock PurchaseQty SalesQty ClosingStock 2016-12-15 Pen 100 500 0 600 2016-12-16 Pen 600 0 0 600 2016-12-17 Pen 600 300 0 900 2016-12-18 Pen 900 0 400 500 2016-12-19 Pen 500 0 0 500 2016-12-20 Pen 500 0 0 500 2016-12-21 Pen 500 0 400 100 2016-12-22 Pen 100 200 100 200
注意:
1.如果数据库表出现问题,请指导我如何处理这种情况。
2.还可以从两个表中找到当前日期库存
答案 0 :(得分:1)
您正在寻找各种数量值的滚动总和。一种方法是使用相关子查询:
SELECT
t1.Date,
mt.MaterialName,
(SELECT OpeningStock FROM [Material Table] WHERE MaterialId = t1.MaterialId) +
COALESCE((SELECT SUM(t2.PurchaseQty - t2.SalesQty) FROM [Material Stock] t2
WHERE t2.Date < t1.Date AND t1.MaterialId = t2.MaterialId), 0) AS OpeningStock,
t1.PurchaseQty,
t1.SalesQty,
(SELECT OpeningStock FROM [Material Table] WHERE MaterialId = t1.MaterialId) +
COALESCE((SELECT SUM(t2.PurchaseQty - t2.SalesQty) FROM [Material Stock] t2
WHERE t2.Date <= t1.Date AND t1.MaterialId = t2.MaterialId), 0) AS ClosingStock
FROM [Material Stock] t1
INNER JOIN [Material Table] mt
ON t1.MaterialId = mt.MaterialId
ORDER BY
mt.MaterialName,
t1.Date;
请注意,将开仓库存值存储在物料库存表的单独表格中是不好的表格设计。这意味着上面的查询将不返回铅笔记录。更好的方法是将种子记录插入到每种材料的材料库存中,其数量为初始库存。
<强>输出:强>
在这里演示:
答案 1 :(得分:0)
只需按以下步骤操作:
SELECT S.DATE, M.MaterialName, M.OpeningStock, S.PurchaseQty, S.SalesQty, SUM((M.OpeningStock+S.PurchaseQty)-S.SalesQty)ClosingStock FROM #TABLE
(
SELECT * FROM MaterialTABLE
) M
INNER JOIN Material S ON S.MaterialId = M.MaterialId where s.date between @FromDate and @Todate