1

我查询了没有库存的产品数量(我知道通过查看制造商返回的带有一些状态代码的订单),按产品、日期和存储,如下所示:

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 ) 中的日期时间函数,但找不到我需要的。

4

2 回答 2

1

可能是我没有正确回答您的问题,但看起来您需要杠杆子查询。

现在我需要按产品和存储获取缺货 2 天或更长时间的产品的出现次数

所以:

SELECT COUNT(*), date, product_id FROM ( YOUR BIG QUERY IS THERE ) a
WHERE a.date < (CURRENT_DATE - interval '2' day)
GROUP BY date, product_id
于 2013-09-27T14:58:24.250 回答
0

由于您似乎希望结果中的每一行都是单独的,因此您无法聚合。改为使用窗口函数来获取每天的计数。众所周知的聚合函数count()也可以用作窗口聚合函数

SELECT current_date - ped.data_envio::date AS days_out_of_stock
      ,count(*) OVER (PARTITION BY ped.data_envio::date)
                                        AS count_per_days_out_of_stock
      ,ped.data_envio::date AS date
      ,p.id                 AS product_id
      ,opl.id               AS storage_id
FROM   sub_produtos_pedidos spp
LEFT   JOIN cad_produtos    p   ON p.cod_ean = spp.ean_produto
LEFT   JOIN sub_pedidos     sp  ON sp.id     = spp.id_pedido
LEFT   JOIN op_logisticos   opl ON opl.id    = sp.id_op_logistico
LEFT   JOIN pedidos         ped ON ped.id    = sp.id_pedido
WHERE  spp.motivo = '201'                   -- code for 'not in inventory'
ORDER  BY ped.data_envio::date, p.id, opl.id

排序顺序:首先是缺货时间最长的产品。
请注意,您只需减去即可在 Postgresdates中得到一个。integer

如果您想要“n 行已在此天数或更长时间内缺货”的意义上的运行计数,请使用:

count(*) OVER (ORDER BY ped.data_envio::date) -- ascending order!
                                        AS running_count_per_days_out_of_stock

您在同一天获得相同的计数,同行被归为一类。

于 2013-09-27T16:41:54.597 回答