首先,简短的忠告:
您的问题非常广泛,因为您已经说明了您想要的,但没有添加任何代码来显示您为实现目标所做的努力 - 这可能会阻止会员为您提供现成的 -提出解决方案,您的问题更有可能被投票结束。
不过,我会扔给你一根骨头,为你指明正确的方向……
查询
然后,您可以构建第 4 个查询,以在来自这三个查询的数据旁边显示产品信息。股票查询 (2) 和 (3) 显然都将从 Closing Stock 表中获取数据,但会针对不同月份配置标准。
1。购买
假设您报告的是上个月,购买查询可能类似于:
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 函数用于计算上个月和当前月份的开始日期,形成购买日期选择标准的日期边界。
2。期初库存
期初库存的查询更加简单,因为不需要汇总,因为一个产品可以在一个月内多次购买,而一个产品永远只有一个任何给定月份的收盘价。
因此,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)
在这里,日期边界计算为上个月的前一个月(即两个月前),因为一个月的收盘股票将是下一个月的开盘股票。 p>
3。收盘。
鉴于上述情况,现在这应该相对简单 - 只需调整上述查询,使日期边界落在上个月内:
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