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

SQL需求:计算商品过去40个季度的平均销售额

Solution to Calculate 40-Quarter Average Sales per Article

Let's break down how to solve this problem efficiently, while accounting for the dynamic date range rule (adjusting if 2019Q4 data is available).

Core Approach

Instead of hardcoding date ranges, we can use window functions to dynamically select the most recent 40 quarters for each article. This automatically handles the rule where if 2019Q4 exists, we shift the range forward—no manual date checks needed.

Step-by-Step SQL Implementation

  1. Rank Quarters by Recency: First, we assign a rank to each sales record per article, with the newest quarter ranked #1.
  2. Filter Top 40 Quarters: We only keep records ranked 1 to 40 (the most recent 40 quarters).
  3. Calculate Average: Finally, we group by article and compute the average of the filtered sales amounts.

Here's the complete SQL query:

SELECT
    AVG(amountofsale) AS Avg,
    article
FROM (
    SELECT
        article,
        amountofsale,
        -- Assign rank: newest quarter = 1, next = 2, etc.
        ROW_NUMBER() OVER (
            PARTITION BY article 
            ORDER BY year DESC, quarter DESC
        ) AS qtr_rank
    FROM table1
) ranked_sales
-- Keep only the most recent 40 quarters per article
WHERE qtr_rank <= 40
GROUP BY article;

Why This Works

  • Dynamic Range Handling: The ROW_NUMBER() window function automatically adjusts to the latest available quarter for each article. If 2019Q4 exists for an article, it becomes rank #1, and the 40th rank will be 2010Q1. If only up to 2019Q3 is available, the 40th rank will be 2009Q4—exactly matching your requirements.
  • Flexibility: This query works even if some articles have missing quarters (though your sample data shows continuous quarters). If you need to enforce exactly 40 quarters (exclude articles with fewer), add HAVING COUNT(*) = 40 after GROUP BY article.

Example Output

Using your sample data, the query will return exactly the expected result:

Avgarticle
33.5article1
70.5article2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:52:28