【发布时间】:2013-09-27 14:25:16
【问题描述】:
我查询了未库存的产品数量(通过查看制造商返回的带有一些状态代码的订单我知道),按产品、日期和存储,看起来像这个:
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) 中的日期时间函数,但找不到我需要的。
【问题讨论】:
-
您需要告诉我们更多关于表之间的关系。这些是1:1的关系吗?还是 1:n?为什么要使用 LEFT JOIN?哪些表不能有匹配的行?
标签: sql postgresql count window-functions