循环 SQL 中的日期

Looping with Dates in SQL

我在 SQL 开发人员工作,计算给定月份月底所有活跃案例的平均金额。按照我写的方式,如果我想要过去一年中每个月的结果,我必须重新运行 代码 12 次:

    -- DEFINE month_end = '28/02/21';
    -- DEFINE month_end = '31/03/21';
    DEFINE month_end = '30/04/21';


    with active_at_month_end as (
         SELECT amount
         FROM table
         WHERE start_date <= '&month_end'
              AND end_date > '&month_end'
         )
   
    SELECT  extract(year from to_date('&month_end','DD/MM/YY')) as year,
            extract(month from to_date('&month_end','DD/MM/YY')) as month,
            avg(amount) as avg_amount
    FROM active_at_month_end 



有什么方法可以重写它(也许使用 for 循环?)所以我只需要 运行 一次就可以得到这样的结果?

Year Month avg_amt
2021 2 ###
2021 3 ###
2021 4 ###

如果您使用的是 Oracle,您可以使用类似下面的内容 -

DECLARE
  month_end DATE := '31-DEC-2020'; -- assuming you want to display output from Jan-21
  no_Of_Months NUMBER := 12; -- if you want to display 12 months 
BEGIN
FOR i IN 1 .. no_Of_Months 
LOOP
month_end := ADD_MONTHS(month_end, 1); -- output will start from Jan-2021

Select year, month, avg(amount) as avg_amount
from 
(SELECT extract(year from month_end) as year,
        extract(month from month_end) as month,
        amount
        FROM table
        WHERE start_date <= month_end
          AND end_date > month_end)
) temp
group by year, month;
END LOOP;
END;