Re: multiple table join and sumation - Mailing list pgsql-novice

From Michael Fuhr
Subject Re: multiple table join and sumation
Date
Msg-id 20041204031147.GA55376@winnie.fuhr.org
Whole thread Raw
In response to multiple table join and sumation  ("Keith Worthington" <keithw@narrowpathinc.com>)
List 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/

pgsql-novice by date:

Previous
From: "Keith Worthington"
Date:
Subject: Null vs empty string
Next
From: Michael Fuhr
Date:
Subject: Re: Null vs empty string