如何检查值是否在几个月内减少SQLite



我每月都有收入,我想要的是查看每个账户的收入,从上次减少到递减顺序下面是查询

SELECT account_id,
monthly_date,
earnings
FROM accounts_revenue
GROUP BY account_id,
monthly_date

数据是这样的

tbody> <<tr>5555555555555555555555
account_idmonthly_dateearnings
552017-01-012000
2017-02-011950
2017-10-012000
2018-02-011500
2018-05-011200
2018-12-013000
2019-01-01900
2019-02-01810
2019-04-011000
2019-05-01600
2020-01-01800
2020-02-01100
1222020-01-01800
1222020-02-01100

使用NOT EXISTS:

SELECT ar1.*
FROM accounts_revenue ar1
WHERE NOT EXISTS (
SELECT 1
FROM accounts_revenue ar2
WHERE ar2.account_id = ar1.account_id 
AND ar2.monthly_date < ar1.monthly_date 
AND ar2.earnings <= ar1.earnings
)
ORDER BY ar1.account_id, ar1.monthly_date;

您可以使用lag()窗口函数和CTE(或子查询,如果您喜欢)来过滤掉您不想要的行:

WITH revenue AS
(SELECT account_id, monthly_date, earnings,
lag(earnings) OVER (PARTITION BY account_id ORDER BY monthly_date) AS prev_earnings
FROM accounts_revenue)
SELECT account_id, monthly_date, earnings
FROM revenue
WHERE earnings < prev_earnings OR prev_earnings IS NULL
ORDER BY account_id, monthly_date;

为了提高效率,您需要在accounts_revenue(account_id, monthly_date)上建立索引。

最新更新