在商店中获取剩余商品

时间:2014-09-25 05:02:16

标签: sql-server

我希望得到一张表:

itemid | remaining_quantity
-------|---------
1      | 100
-------|---------
3      | 150
-------|---------
4      | 300

重要表格:

  • 我们是否收到了purshase(id,itemid,quantity,isReceived)?

  • 销售(id,itemid,quantity,isReceived)//是否被客户收到?

  • 项目(id,init_quantity)

  • LostItem(id,itemid,quantity)//如果实际增加或减少,则用于修复实际数量

正如您所看到的,我们应该只考虑那些isReceived = True的销售和追求。在LostItem中,数量可能为负数,表示实际数量小于计算数量。它也可能是积极的,意味着实际的计算结果更多。

(即我想获得Purshase - Sale + LostItem +项目)

这是我到目前为止所做的:(导致没有行)

select i.itemid, 
      isnull(sum(p.quantity), 0) - isnull(sum(s.quantity), 0)
        + isnull(sum(t.quantity), 0) + isnull(sum(i.itemInitQuantity), 0)
    as remaining_quantity
from [Purshase] p, [Sale] s, [LostItem] t, [Item] i
where p.pitem = i.itemid and s.saleitem = i.itemid and t.item = i.itemid
      and p.isReceived = 1 and s.isReceived = 1
group by i.itemid

1 个答案:

答案 0 :(得分:0)

发现它!!! (Alhamdu lellah)

SELECT itemid, init, sales_all, sales_mostlma, purchases_all,
purchases_mstlma, taswiyah, sales_mardood, purchases_mardood, 
sales_request, pruchases_request,init - sales_mostlma + purchases_mstlma + 
taswiyah + sales_mardood - purchases_mardood AS stock, init - sales_all + 
purchases_all + taswiyah + sales_mardood - purchases_mardood AS available, 
init - sales_all + purchases_all + taswiyah + sales_mardood - 
purchases_mardood -  sales_request + pruchases_request 
AS available_with_request
FROM (SELECT itemid,itemInitQuantity AS init,
(SELECT ISNULL(SUM(salequantity), 0) AS cnt FROM dbo.Sale AS s
WHERE (saleitem = i.itemid) AND (tasleemTime IS NOT NULL)) AS sales_mostlma,
(SELECT ISNULL(SUM(salequantity), 0) AS cnt FROM dbo.Sale AS s
WHERE (saleitem = i.itemid)) AS sales_all,
(SELECT ISNULL(SUM(pcquantity), 0) AS cnt FROM dbo.Purshase AS p
WHERE (pitem = i.itemid) AND (tasleemTime IS NOT NULL)) AS purchases_mstlma,
(SELECT ISNULL(SUM(pcquantity), 0) AS cnt FROM dbo.Purshase AS p
WHERE (pitem = i.itemid)) AS purchases_all, 
(SELECT ISNULL(SUM(quantity), 0) AS cnt FROM dbo.TaswiyahGardiyah AS t
WHERE (item = i.itemid)) AS taswiyah,
(SELECT ISNULL(SUM(sm.smquantity), 0) AS Expr1 FROM dbo.SaleMardood AS sm 
INNER JOIN dbo.Sale AS ss ON sm.smsale = ss.saleid
WHERE (ss.saleitem = i.itemid)) AS sales_mardood,
(SELECT        ISNULL(SUM(pm.purmquantity), 0) AS Expr1 
FROM dbo.PurshaseMardood AS pm 
INNER JOIN dbo.Purshase AS pur ON pm.purmpurshase = pur.pid
WHERE (pur.pitem = i.itemid)) AS purchases_mardood,
(SELECT ISNULL(SUM(prquantity), 0) AS Expr1 FROM dbo.PurshaseRequest AS pr
WHERE (pritem = i.itemid)) AS pruchases_request,
(SELECT ISNULL(SUM(scquantity), 0) AS Expr1 FROM dbo.SaleRequest AS sr
WHERE (scitem = i.itemid)) AS sales_request
FROM dbo.Item AS i) AS myTable