Re: Help : Sum 2 tables based on key from other table

From: Elliot <yields(dot)falsehood(at)gmail(dot)com>
To: Ken Tanzer <ken(dot)tanzer(at)gmail(dot)com>, rod(at)iol(dot)ie
Cc: Hengky Liwandouw <hengkyliwandouw(at)gmail(dot)com>, PostgreSQL general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Help : Sum 2 tables based on key from other table
Date: 2013-11-18 17:02:09
Message-ID: 528A4811.5070001@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 2013-11-18 04:37, Ken Tanzer wrote:
> 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:
>
> SELECT
> a.product_id,
> a.product_name,
> b.initial_stock_sum,
> c.in_out_sum,
> c.in_sum,
> c.out_sum
> FROM
> a
> LEFT JOIN
> (SELECT
> product_id,
> SUM(initial_stock) AS initial_stock_sum
> FROM b
> GROUP BY product_id
> ) b USING (product_id)
> LEFT JOIN
> (SELECT
> product_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_sum
> FROM c
> GROUP BY product_id
> ) c USING (product_id)
> WHERE a.supplier_id='XXX';
>
> Cheers,
> Ken
>
I'm a big fan of using LATERAL joins (9.3+) for this use case.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Jeff Janes 2013-11-18 17:31:31 Re: Suggestion: pg_dump self-cleanup if out-of-disk
Previous Message Jeff Janes 2013-11-18 16:44:45 Re: Postgres as In-Memory Database?