SELECT * from (SELECT a.company_to_id,d.name,a.product_id,COALESCE(c.name,''),sum(a.cnt)as out_cnt,sum(COALESCE(b.cnt,0)) as in_cnt from
( SELECT count(*)cnt,company_to_id,product_id from stkdetails.c19257 WHERE vtype_id = 2 GROUP BY company_to_id,product_id)A
( SELECT count(*)cnt,company_to_id,product_id from stkdetails.c{company_id} WHERE vtype_id = 2 GROUP BY company_to_id,product_id)A
left outer JOIN (SELECT count(*)cnt,company_id,product_id from stkdetails.c19257 WHERE vtype_id = 1 and company_id != {company_id} GROUP BY company_id,product_id)b on b.company_id = a.company_to_id and a.product_id = b.product_id
LEFT outer join (SELECT id,name from logistics.product_product)c on c.id = a.product_id
LEFT outer join (SELECT id,name from logistics.company_company WHERE ancestor_id = {company_id} or id in(11013,11014) )d on d.id = a.company_to_id
GROUP BY a.company_to_id,d.name,a.product_id,c.name )a
cur.execute("SELECT id FROM logistics.inventory_stack WHERE code = '"+code+"' and company_id = "+str(company_id))
stack=cur.fetchone()
ifstack:
s=f'''
select a.id,a.code,b.id,b.name,c.id,c.name,d.stacks from (SELECT id,code,product_id,store_id FROM logistics.inventory_stack WHERE company_id = {str(company_id)} and code = '{code}' )a
left outer join (select id,name from logistics.inventory_storehouse)b on b.id = a.store_id
left outer join (select id,name from logistics.product_product)c on c.id = a.product_id
LEFT OUTER JOIN ( SELECT COUNT ( * )stacks,stack_id FROM logistics.inventory_stackdetails GROUP BY stack_id ) d ON d.stack_id = A.ID