Re: running totals with end of month line

From: David Johnston <polobo(at)yahoo(dot)com>
To: "M(dot) D(dot)" <lists(at)turnkey(dot)bz>
Cc: "pgsql-sql(at)postgresql(dot)org" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: running totals with end of month line
Date: 2011-12-01 01:12:22
Message-ID: E71E635E-4A47-46BF-8899-78D1837D6FBA@yahoo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Nov 30, 2011, at 20:03, "M. D." <lists(at)turnkey(dot)bz> wrote:

> Hi everyone,
>
> I would like to create a query that does a running total for each account, but I also want to show a 'phantom' row that gives the end of month with the last day of the month as the transaction date.
>
> Here's a sample query:
> SELECT n.customer_id, n.order_id, n.order_total,
> COALESCE(SUM(o.order_total),0) As past_order_total
> FROM orders AS n LEFT JOIN orders AS o
> ON (o.customer_id = n.customer_id
> AND n.order_datetime > o.order_datetime)
> GROUP BY n.customer_id, n.order_datetime, n.order_id, n.order_total
> ORDER BY n.customer_id, n.order_datetime, n.order_id;
>
> --- taken from http://bit.ly/speZzs
>
> Is there a way to have that 'phantom' row for each account? I want to result to be ordered by customer_id, account_type.
>
> More details:
> In my situation, I have Customers and Grain types.
> I want to generate a result that will show Customer, Grain Type, Daily Avg Bal, Charge Rate, discount, Charge.
> Maybe it's not really possible. I see it a bit hard group it properly, showing only single row per customer per grain.
>
>
> Many thanks,
> Mark
You need to write the totaling query and then UNION ALL it with the detail query. You probably will want to use WINDOW aggregates as well - assuming you are on 8.4 or better.

David J.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Filip Rembiałkowski 2011-12-01 12:07:02 Re: plpgsql: how to get the exception's detail information?
Previous Message M. D. 2011-12-01 01:03:29 running totals with end of month line