Re: group by with sum and sum till max date

Поиск
Список
Период
Сортировка
От Samuel Gendler
Тема Re: group by with sum and sum till max date
Дата
Msg-id CAEV0TzBfCGwd-QX5vj0J=ufra-iPByvf78KMYuSoD3Htr1wqxw@mail.gmail.com
обсуждение исходный текст
Ответ на group by with sum and sum till max date  ("M. D." <lists@turnkey.bz>)
Список pgsql-sql


On Tue, Jul 5, 2011 at 10:42 AM, M. D. <lists@turnkey.bz> wrote:
This is a little hard to explain, and I'm not sure if it's possible, but here goes.

This is my query:
select year, month,
(select number from account where account.account_id = view_account_change.account_id) as number,
(select name from account where account.account_id = view_account_change.account_id) as account,
sum(amount) as amount
from view_account_change
where view_account_change.change_date >= '2010-01-01'
group by year,month,  number, account
order by year,month, number, account

I want to make an exception for the sum so that if the account number is less than 4000, I want a sum of all transactions until the last date of the group by.

the query for that would be:
Select sum(amount) from view_account_change where change_date > "max date in the group"

I think you are looking for a window function, but I'm not sure about using a value computed over a window in the where clause. You may have to do something somewhat complicated with a subquery, but you can definitely compute 'max date in the group' via a window function:


You'll like have to split it into a UNION of 2 queries, one for account numbers lower than 4000 and the other for the rest.

Perhaps select max date in the group in a subquery which you then join to in an outer query.  That should be enough to start experimenting with, anyway.

В списке pgsql-sql по дате отправления:

Предыдущее
От: Kevin Crain
Дата:
Сообщение: Re: interesting sequence
Следующее
От: Jasen Betts
Дата:
Сообщение: Re: interesting sequence