Re: multiple table join and sumation

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Keith Worthington <keithw(at)narrowpathinc(dot)com>
Cc: PostgreSQL Novice <pgsql-novice(at)postgresql(dot)org>
Subject: Re: multiple table join and sumation
Date: 2004-12-04 03:11:47
Message-ID: 20041204031147.GA55376@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

On Fri, Dec 03, 2004 at 06:16:32PM -0500, Keith Worthington wrote:

> id | committed | on_order
> ------+-----------+---------
> A | 15 | 10
> B | 9 | 5
> C | 0 | 0
> D | 0 | 0
> E | 0 | 2

The following gives the above results when used against your example
data. I look at it and think it ought to be simpler, so maybe somebody
will post an improvement.

SELECT i.id,
COALESCE(s.sum, 0) AS committed,
COALESCE(p.sum, 0) AS on_order
FROM tbl_item AS i
LEFT OUTER JOIN (
SELECT id, SUM(quantity)
FROM tbl_sales_item JOIN tbl_sales USING ("order")
WHERE closed IS FALSE
GROUP BY id
) AS s USING (id)
LEFT OUTER JOIN (
SELECT id, SUM(quantity)
FROM tbl_purchase_item JOIN tbl_purchase USING ("order")
WHERE closed IS FALSE
GROUP BY id
) AS p USING (id)
ORDER BY id;

BTW, when providing example data, it's helpful if you post SQL
statements that create and populate the example tables. That way
people can paste those statements into their own database and verify
their solutions against your data.

--
Michael Fuhr
http://www.fuhr.org/~mfuhr/

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Michael Fuhr 2004-12-04 03:27:56 Re: Null vs empty string
Previous Message Keith Worthington 2004-12-04 01:57:24 Null vs empty string