Re: Help : Sum 2 tables based on key from other table
От | Elliot |
---|---|
Тема | Re: Help : Sum 2 tables based on key from other table |
Дата | |
Msg-id | 528A4811.5070001@gmail.com обсуждение исходный текст |
Ответ на | Re: Help : Sum 2 tables based on key from other table (Ken Tanzer <ken.tanzer@gmail.com>) |
Список | pgsql-general |
On 2013-11-18 04:37, Ken Tanzer wrote:
I'm a big fan of using LATERAL joins (9.3+) for this use case.If the tables aren't huge, you're not concerned about optimization, and you just want to get your numbers, I think something like this would do the trick. I haven't actually tried it 'cause I didn't have easy access to your tables:SELECTa.product_id,a.product_name,b.initial_stock_sum,c.in_out_sum,c.in_sum,c.out_sumFROMaLEFT JOIN(SELECTproduct_id,SUM(initial_stock) AS initial_stock_sumFROM bGROUP BY product_id) b USING (product_id)LEFT JOIN(SELECTproduct_id,sum(CASE WHEN date < 'BEGINNING DATE' THEN in-out ELSE 0 END) AS in_out_sum,sum(CASE WHEN date BETWEEN 'BEGINNING DATE' AND 'ENDING DATE' THEN in ELSE 0 END) AS in_sum,sum(CASE WHEN date BETWEEN 'BEGINNING DATE' AND 'ENDING DATE' THEN out ELSE 0 END) AS out_sumFROM cGROUP BY product_id) c USING (product_id)WHERE a.supplier_id='XXX';Cheers,Ken
В списке pgsql-general по дате отправления: