计算 table 中的数字变化
Calculate the number change in the table
我有一个 table 设置如下,它只捕获当天的总余额:
+--------+------------+--------+
| id | date | wallet |
+----+---------+----------+-----
| 10056 | 2022-03-01 | 120 |
| 10056 | 2022-03-02 | 40 |
| 10056 | 2022-03-04 | 80 |
| 10056 | 2022-03-08 | 23 |
| 13572 | 2022-03-01 | 20 |
| 13572 | 2022-03-03 | 17 |
+--------+------------+--------+
请问是否可以只计算支出?我只能想着用'CASE'来停止计算比昨天小的数,但是我不知道如何逐行计算负数。这应该是结果:
-- March Spending per user
+---------+---------+
| id | spend |
+---------+---------+
| 10056 | 103 |
| 13572 | 3 |
+---------+---------+
我不确定我的SQL概念是否正确。
一种选择是计算连续钱包值之间的差异,然后排除负值(因为它们是钱包收入而不是支出)并求和。检查以下查询:
WITH cte AS (
SELECT *,
wallet - LEAD(wallet) OVER(PARTITION BY id
ORDER BY date) AS diff
FROM balances
)
SELECT id,
SUM(diff)
FROM cte
WHERE diff > 0
GROUP BY id
试试看 here.
如果我能很好地解释你的问题,你必须分两个阶段解决问题:
- 将前一行的钱包值添加到每一行,以便您可以应用正确的逻辑。
- 应用允许您获取字段值并将它们分组的逻辑。
假设生成名为 prova 的原始 table,
我的查询建议可以是:
select id, sum(case when prev_wallet>wallet then prev_wallet- wallet else 0 end) expense
from
(
select p.id, p.date, p.wallet, (select wallet from prova where id=p.id and date = (select max(date) date from prova where date<p.date and id=p.id)) prev_wallet
from prova p
order by p.id, p.date
) A
group by id
再见
我有一个 table 设置如下,它只捕获当天的总余额:
+--------+------------+--------+
| id | date | wallet |
+----+---------+----------+-----
| 10056 | 2022-03-01 | 120 |
| 10056 | 2022-03-02 | 40 |
| 10056 | 2022-03-04 | 80 |
| 10056 | 2022-03-08 | 23 |
| 13572 | 2022-03-01 | 20 |
| 13572 | 2022-03-03 | 17 |
+--------+------------+--------+
请问是否可以只计算支出?我只能想着用'CASE'来停止计算比昨天小的数,但是我不知道如何逐行计算负数。这应该是结果:
-- March Spending per user
+---------+---------+
| id | spend |
+---------+---------+
| 10056 | 103 |
| 13572 | 3 |
+---------+---------+
我不确定我的SQL概念是否正确。
一种选择是计算连续钱包值之间的差异,然后排除负值(因为它们是钱包收入而不是支出)并求和。检查以下查询:
WITH cte AS (
SELECT *,
wallet - LEAD(wallet) OVER(PARTITION BY id
ORDER BY date) AS diff
FROM balances
)
SELECT id,
SUM(diff)
FROM cte
WHERE diff > 0
GROUP BY id
试试看 here.
如果我能很好地解释你的问题,你必须分两个阶段解决问题:
- 将前一行的钱包值添加到每一行,以便您可以应用正确的逻辑。
- 应用允许您获取字段值并将它们分组的逻辑。
假设生成名为 prova 的原始 table, 我的查询建议可以是:
select id, sum(case when prev_wallet>wallet then prev_wallet- wallet else 0 end) expense
from
(
select p.id, p.date, p.wallet, (select wallet from prova where id=p.id and date = (select max(date) date from prova where date<p.date and id=p.id)) prev_wallet
from prova p
order by p.id, p.date
) A
group by id
再见