with t1 as (
select
account_id,amount,year(day)as year,substr(day,6,2)as month
from transactions where type = 'creditor'
order by account_id,year,month )
, t2 as(
select t1.account_id,sum(amount)total,year,month,max_income from t1,accounts
where t1.account_id = Accounts.account_id
group by account_id, year, month,max_income
order by account_id)
select account_id,total,year,month,max_income,row_number() over (partition by account_id order by month)r1
from t2
where total > max_income
with t1 as (
select
account_id,amount,year(day)as year,substr(day,6,2)as month
from transactions where type = 'creditor'
order by account_id,year,month )
, t2 as(
select t1.account_id,sum(amount)total,year,month,max_income from t1,accounts
where t1.account_id = Accounts.account_id
group by account_id, year, month,max_income
order by account_id)
, t3 as (
select account_id,total,year,month,max_income,row_number() over (partition by account_id order by month)r1
from t2
where total > max_income)
# , t4 as (
select account_id,year,(month-r1) as m2,count((month-r1)) as r3
from t3
group by account_id ,year,(month-r1)
having (count((month-r1))) >=2
图解:
代码:
sql复制代码
with t1 as (
select
account_id,amount,year(day)as year,substr(day,6,2)as month
from transactions where type = 'creditor'
order by account_id,year,month )
, t2 as(
select t1.account_id,sum(amount)total,year,month,max_income from t1,accounts
where t1.account_id = Accounts.account_id
group by account_id, year, month,max_income
order by account_id)
, t3 as (
select account_id,total,year,month,max_income,row_number() over (partition by account_id order by month)r1
from t2
where total > max_income)
, t4 as (
select account_id,year,(month-r1) as m2,count((month-r1)) as r3
from t3
group by account_id ,year,(month-r1))
select distinct account_id from t4
where r3 >=2
;