You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写SQL查询生成table表的Daily Change日余额差值列?

Calculate Daily Change Using Previous Day's Balance

First, let's recap your table structure and sample data to make sure we're aligned:

BalanceValue 1Value2DateDaily Change (Expected)
88,648,668.6012,620,390.513/27/2018-1
73,087,707.303,494,174.703/28/2018-1
63,039,443.512,345,356.153/29/2018-1

Your goal is to compute Daily Change as the difference between the current day's Balance and the prior day's Balance (e.g., 3/28's balance minus 3/27's gives 7-8=-1, which matches your expected result).

Solution Using Window Functions

The most efficient and clean way to do this in modern SQL is with the LAG() window function—no messy self-joins required. Here's the query:

SELECT
    Balance,
    `Value 1`,
    `Value2`,
    Date,
    Balance - LAG(Balance, 1) OVER (ORDER BY STR_TO_DATE(Date, '%m/%d/%Y')) AS `Daily Change`
FROM
    `table`
ORDER BY
    STR_TO_DATE(Date, '%m/%d/%Y');

Query Breakdown:

  • LAG(Balance, 1): This pulls the Balance value from the immediately preceding row relative to the current one.
  • OVER (ORDER BY STR_TO_DATE(Date, '%m/%d/%Y')): We sort rows chronologically by converting the string Date to a proper date type (critical to avoid sorting errors like 10/1 coming before 3/27). If your Date column is already a date/time data type, simplify this to ORDER BY Date.
  • Balance - LAG(...): Subtracts the prior day's balance from the current day's to get the daily change.

Quick Adjustments:

  • For the first row (3/27/2018), there's no prior day data, so Daily Change will return NULL. If you want to set this to 0 instead, use COALESCE():
    Balance - COALESCE(LAG(Balance, 1) OVER (ORDER BY STR_TO_DATE(Date, '%m/%d/%Y')), Balance) AS `Daily Change`
    
    This makes the first day's change 0 by subtracting the balance from itself.

Sample Output:

Running the base query on your data gives:

BalanceValue 1Value2DateDaily Change
88,648,668.6012,620,390.513/27/2018NULL
73,087,707.303,494,174.703/28/2018-1
63,039,443.512,345,356.153/29/2018-1

内容的提问来源于stack exchange,提问作者user8162541

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:01:17