SQL中的日期循环
我在SQLDeveloper工作,计算给定月底所有活动案例的平均金额。按照我的编写方式,如果我想得到过去一年中每个月的结果,我必须重新运行代码12次:SQL中的日期循环,sql,loops,date,oracle-sqldeveloper,Sql,Loops,Date,Oracle Sqldeveloper,我在SQLDeveloper工作,计算给定月底所有活动案例的平均金额。按照我的编写方式,如果我想得到过去一年中每个月的结果,我必须重新运行代码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
-- 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循环重写它?所以我只需要运行一次就可以得到这样的结果
年
月
平均金额
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;
用你正在使用的数据库标记你的问题,这看起来很有希望!我还没有完全弄明白,但我应该能从这里弄明白。谢谢您: