我目前的设置:
产品表
购买表
关闭股票
我想创建一个查询,列出产品,购买总数和每个月末的结算数量的所有PNAME
。在下个月结束时,上个月的期末存货将是该月的期初存货。
购买发生在整个月份,我们在每个月的最后一天收盘。我尝试使用查询向导并导入产品中的PNAME
,来自Purchases的Quantity
和来自Closing Stock的Quantity
,但我只获得了购买的总数和结算库存的总数为空。
首先,简短的建议:
您的问题非常广泛,因为您已说出您想要的内容,但没有提供任何显示您努力实现目标的代码 - 这可能会阻止成员向您提供现成的解决方案,而您的问题更可能是投票结束。
不过,我会告诉你一个骨头,指出你正确的方向......
UPC
字段是Products
表中的主键,则应使用此字段(而不是PNAME
字段)在Purchases
表和Closing Stock
表中引用您的产品,以便可以唯一标识每个项目。然后,您可以构建第4个查询,以显示产品信息以及这三个查询中的数据。库存查询(2)和(3)显然都会从Closing Stock
表中获取数据,但标准配置为不同月份。
假设您在上个月报告,购买查询可能类似于:
select
pu.upc, sum(pu.quantity) as puqty
from
purchases pu
where
pu.purdate >= dateserial(year(date),month(date)-1,1) and
pu.purdate < dateserial(year(date),month(date),1)
group by
pu.upc
这里,DateSerial
函数用于计算上一个和当前月份的开始日期,形成购买日期选择标准的日期边界。
对开仓库存的查询甚至更简单,因为不需要聚合,因为产品可以在一个月内多次购买,产品将只有任何给定月份的单一结算库存数字。
因此,Opening Stock查询可能类似于:
select
os.upc, os.quantity as osqty
from
[closing stock] os
where
os.enddate >= dateserial(year(date),month(date)-2,1) and
os.enddate < dateserial(year(date),month(date)-1,1)
这里,日期边界被计算为上个月之前的月份(即两个月前),因为一个月的结算库存将是下一个月的期初库存。
鉴于上述情况,现在应该相对简单 - 只需调整上述查询,使日期边界在上个月内:
select
cs.upc, cs.quantity as csqty
from
[closing stock] cs
where
cs.enddate >= dateserial(year(date),month(date)-1,1) and
cs.enddate < dateserial(year(date),month(date),1)
现在您构建了上述三个查询以报告上个月内的购买,开仓和关闭库存,现在我们可以使用一个最终查询将所有三个联系在一起。
为此,我们将在上面构建的每个查询中使用带有Products
的LEFT JOIN
表,因为我们总是希望每个产品都出现在结果中,无论产品是否在上个月内购买。
因此,在伪代码中,查询看起来像:
select
p.upc,
p.pname,
purchases.puqty,
openingstock.osqty,
closingstock.csqty
from
(
(
products p left join purchases on p.upc = purchases.upc
)
left join openingstock on p.upc = openingstock.upc
)
left join closingstock on p.upc = closingstock.upc
然后我们可以在这段代码中注入我们之前对每个查询的定义,以产生最终的结果(希望这是有效的,因为我绝对没有测试过这个!):
select
p.upc,
p.pname,
purchases.puqty as [Purchased Qty],
openingstock.osqty as [Opening Stock],
closingstock.csqty as [Closing Stock]
from
(
(
products p left join
(
select
pu.upc, sum(pu.quantity) as puqty
from
purchases pu
where
pu.purdate >= dateserial(year(date),month(date)-1,1) and
pu.purdate < dateserial(year(date),month(date),1)
group by
pu.upc
)
purchases on p.upc = purchases.upc
)
left join
(
select
os.upc, os.quantity as osqty
from
[closing stock] os
where
os.enddate >= dateserial(year(date),month(date)-2,1) and
os.enddate < dateserial(year(date),month(date)-1,1)
)
openingstock on p.upc = openingstock.upc
)
left join
(
select
cs.upc, cs.quantity as csqty
from
[closing stock] cs
where
cs.enddate >= dateserial(year(date),month(date)-1,1) and
cs.enddate < dateserial(year(date),month(date),1)
)
closingstock on p.upc = closingstock.upc