我查询了没有库存的产品数量(我知道通过查看制造商返回的带有一些状态代码的订单),按产品、日期和存储,如下所示:
SELECT count(*) as out_of_stock,
prod.id as product_id,
ped.data_envio::date as date,
opl.id as storage_id
from sub_produtos_pedidos spp
left join cad_produtos prod ON spp.ean_produto = prod.cod_ean
left join sub_pedidos sp ON spp.id_pedido = sp.id
left join pedidos ped ON sp.id_pedido = ped.id
left join op_logisticos opl ON sp.id_op_logistico = opl.id
where spp.motivo = '201' -- this is the code that means 'not in inventory'
group by storage_id,product_id,date
这会产生这样的答案:
out_of_stock | product_id | date | storage_id
--------------|------------|-------------|-------------
1 | 5 | 2012-10-16 | 1
5 | 4 | 2012-10-16 | 2
现在我需要按产品和存储来获取缺货 2 天或更长时间、5 天或更长时间等产品的出现次数。
所以我想我需要对第一个查询进行新的计数,在某些定义的天间隔内聚合结果行。
我尝试查看 Postgres ( http://www.postgresql.org/docs/7.3/static/functions-datetime.html ) 中的日期时间函数,但找不到我需要的。