计算股票 OpeningQuantity、QuantityIn、QuantityOut 和 ClosingQuantity

问题描述

我有两个表 Item 和 LineItem。

项目表

ItemId 姓名 数量
1 洗发水 2
2 肥皂 0

行项目表

LineItemId ItemId 数量 数量 创建日期
1 1 1 0 2021-05-04
2 1 1 0 2021-05-05

现在,如果我想使用查询返回 2021-05-01 和 2021-05-04 之间的 openingQuantity、QuantityIn、QuantityOut 和 CurrentQuantity,它应该像这样返回:

ItemId 姓名 起始数量 数量 数量 当前数量
1 洗发水 0 1 1

如果我想使用查询返回 2021-05-04 和 2021-05-05 之间的 openingQuantity、QuantityIn、QuantityOut 和 CurrentQuantity,它应该像这样返回:

ItemId 姓名 起始数量 数量 数量 当前数量
1 洗发水 1 1 2
select
    items.ItemId as id,items.name as name,(
        select sum(quantityin - quantityout)
        from lineitems
        where
            ItemId = items.ItemId
            and datecreated < '2021-05-04'
    ) as beginning,(
        select sum(quantityin)
        from lineitems
        where
            ItemId = items.ItemId
            and datecreated >= '2021-05-04'
            and datecreated <= '2021-05-04'
    ) as quantity_in,(
        select sum(quantityout)
        from lineitems
        where
            ItemId = items.ItemId
            and datecreated >= '2021-05-04'
            and datecreated <= '2021-05-04'
    ) as quantity_out,(
        (
            select sum(quantityin - quantityout)
            from lineitems
            where
                ItemId = items.ItemId
                and datecreated < '2021-05-04'
        ) + sum(lineitems.QuantityIn - lineitems.QuantityOut)
    ) as closing_quantity
from
    items
    inner join LineItems as lineitems on items.itemid = LineItems.itemid
where
    lineitems.DateCreated >= '2021-05-04'
    and lineitems.DateCreated <= '2021-05-04'
group by
    items.name,items.ItemId

我试过这个查询,它使用子查询提取每列数据,但 Closed_quantity 没有返回任何内容,而且这个查询似乎效率不高,因为对于 begin_quantity,我们必须从上面的日期搜索整个表,直到第一条记录并求和

谁能帮助我应该使用什么查询或重新设计表格。

解决方法

如果我理解正确,这就是你想要做的:

select   
    items.ItemId,items.name,coalesce(sum(quantityin-quantityout) filter (where DateCreated <= '2021-05-01'),0)  beginning,sum(quantityin) filter (where DateCreated > '2021-05-01') QuantityIn,sum(quantityout) filter (where DateCreated > '2021-05-01') QuantityOut,sum(quantityin - quantityout)  CurrentQuantity
from items
inner join LineItems 
    on items.itemid = LineItems.itemid
where lineitems.DateCreated <= '2021-05-04'
group by
    items.name,items.ItemId;

我用 postgresql 语法写的,这里是标准的 sql 语法:

select   
    items.ItemId,sum(case when DateCreated <='2021-05-01' then quantityin-quantityout else 0 end) beginning,sum(case when DateCreated > '2021-05-01' then quantityin else 0 end) QuantityIn,sum(case when DateCreated > '2021-05-01' then quantityout else 0 end) QuantityOut,items.ItemId;