Answer the question
In order to leave comments, you need to log in
How to set a window in a table to a value of 0 in a field?
There is a card_info table:
Клиент Дата Баланс
1 01.03.2010 150
1 02.03.2010 100
1 03.03.2010 200
1 04.03.2010 0
1 05.03.2010 50
1 06.03.2010 0
2 16.03.2010 1000
2 17.03.2010 0
Клиент Дата1 дата2 Баланс
1 01.03.2010 03.03.2010 150
1 05.03.2010 05.03.2010 50
2 16.03.2010 16.03.2010 1000
Answer the question
In order to leave comments, you need to log in
I probably overcomplicated, but so far it turned out like this (DBMS - Postgres):
select client_id, st, en, avg(bal)
from (
select *,
max(day) filter (where l = 1) over (partition by client_id order by day) st,
min(day) filter (where r = 1) over (partition by client_id order by day range between current row and unbounded following) en
from (
select *,
case when (lag(bal) over w) > 0 then 0 else 1 end as l,
case when (lead(bal) over w) > 0 then 0 else 1 end as r
from balance
window w as (partition by client_id order by day)
) t
where bal > 0
) t1 group by client_id, st, en
order by 1, 2
SELECT Client, AVG(Balance) AS AverageBalance WHERE Balance>0 GROUP BY Client
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question