我的一个客户对OpenERP有疑问。我需要为它们构建一个自定义对象,因为它们有问题,有时候它们在销售后会得到退回的产品。因此,我需要将其标记为负数,并从之前的总销售额中扣除。
SELECT sum(rsm1.product_qty_out) as "out"
, sum(rsm2.product_qty_in) as "in"
, rsm2.location_id
, rsm2.product_id
, rsm2.month
from report_stock_move as rsm1, report_stock_move as rsm2
where rsm2.location_id in (
select id
from stock_location
where "name" = 'Consumers'
)
and rsm1.location_id not in (
select id
from stock_location
where "name" = 'Consumers'
)
and rsm1.location_dest_id = rsm2.location_id
and rsm2.location_dest_id = rsm1.location_id
and rsm1.state = 'done' -- both are in done state
and rsm2.state = rsm1.state
group by rsm2.location_id, rsm2.month, rsm2.product_id
;
有人有什么想法吗?另外,根据我用于分组的表格,我会得到不同的结果。那是为什么?
修改 对不起,我急于解决这个问题,我似乎已经说清楚了。具有来自stock_location表的消费者的location_id的report_stock_moves需要为负数,并总结为具有另一个地方的location_id的report_stock_moves,但Consumer是location_dest_id。
示例:
location_id = Some Place (actually ID of stock_location of course)
product_qty = 8
location_dest_id Consumers
date = 2012-07-02
location_id = Consumer
product_qty = 4
location_dest_id Some Place
date = 2012-07-04
以下是两个记录示例。他们有不同的日期,所以我可能想要最大日期或退货日期(从消费者到某个地方),如果我想要联合或分组它们,以便当它们放在一起时,我得到4,而不是说如果我没有将它们放在一起,而只是看看消费者会发生什么。
答案 0 :(得分:1)
以防万一有人为此而挣扎。我会在这里粘贴我的答案。如果有人能帮我解释一下为什么这里的工会似乎都有效,我全都听见了。我可以做简单的SQL,但我不太了解联合如何工作,特别是在这种情况下。
select max(total.id) as id,
sum(total.product_qty) as product_qty,
total.location_id as location_id,
total.date as "date",
total.year as year,
total.month as month,
total.day as day,
total.product_id as product_id
from (
-- From Consumer back to location
select -max(id) as id,
-sum(product_qty) as product_qty,
location_dest_id as location_id,
"date", year, month, day, product_id
from report_stock_move
where location_id in (
select id
from stock_location
where "name" = 'Consumers'
)
and "state" = 'done'
group by location_dest_id, "date", year, month, day, product_id
union all
-- From Location to Consumer
select max(id) as id,
sum(product_qty) as product_qty,
location_id, "date", year, month, day, product_id
from report_stock_move
where location_id not in (
select id
from stock_location
where "name" = 'Consumers'
)
and "state" = 'done'
and location_dest_id in (
select id
from stock_location
where "name" = 'Consumers'
)
group by location_id, "date", year, month, day, product_id
) as total
group by location_id, "date", year, month, day, product_id