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

如何通过关联查询计算工作日销售额较上一工作日的变动值

Calculate Net Sales Change vs Previous Working Day (Skipping Weekends)

Got it, let's break this down. First, let's confirm your source data and expected output to align on what we're building:

Original Sales Data

dateItemnet_sale
2023/01/02Milk500
2023/01/03Milk700
2023/01/04Milk600
2023/01/05Milk300
2023/01/06Milk1100
2023/01/09Milk900
2023/01/10Milk1000
2023/01/11Milk800

Expected Output

dateItemnet_salechange
2023/01/02Milk500NULL
2023/01/03Milk700200
2023/01/04Milk600-100
2023/01/05Milk300-300
2023/01/06Milk1100800
2023/01/09Milk900-200
2023/01/10Milk1000100
2023/01/11Milk800-200

Solution SQL

The trick here is using the LAG() window function—it's perfect for this scenario because it automatically grabs the most recent prior row in your ordered dataset. Since weekends don't have entries in your table, LAG() skips right over them and pulls the last valid working day's sales, no extra weekend-handling logic needed.

Here's the query (swap your_sales_table with your actual table name):

SELECT
    date,
    Item,
    net_sale,
    net_sale - LAG(net_sale) OVER (PARTITION BY Item ORDER BY date) AS change
FROM
    your_sales_table
ORDER BY
    date;

How It Works

  • PARTITION BY Item: Makes sure we only compare sales for the same product (super useful if you add more items to your table later).
  • ORDER BY date: Tells LAG() to look at rows in chronological order, so it always picks the immediate prior working day (even when weekends are missing, like between 2023/01/06 and 2023/01/09).
  • net_sale - LAG(net_sale): Calculates the difference between the current day's sales and the previous working day's sales. The first row returns NULL because there's no prior data, which matches your expected output exactly.

This works across all modern SQL databases (MySQL 8+, PostgreSQL, SQL Server, etc.) without any extra complexity.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 18:15:37