PostgreSQL 按月统计数据
PostgreSQL About 729 words需求
统计从年初到当前月的每月数据。
如果是历年数据则完整统计1-12
月,如果是今年数据则统计1
到当前月(如:1-10
月)。
generate_series
使用PostgreSQL
的内置方法generate_series
生成序列,然后left join
需要统计的表的数据,并关联相应的月份。
SQL
使用extract
从current_date
中提取年份(extract(year from current_date)
都是PostgreSQL
内置方法和关键字,extract
返回的是numeric
)。
select gs as month, COALESCE(sum(ar.amount) filter ( where category = 'xxx' ), 0) as xxx,
COALESCE(sum(ar.amount) filter ( where category = 'yyy' ), 0) as yyy
from generate_series(
1,
case
when
extract(year from current_date)::int = 2024
then extract(month from current_date)::int
else 12
end
) gs
left join a_record ar
on gs = ar.month and ar.year = 2024
group by gs
order by gs desc;
Views: 49 · Posted: 2025-10-04
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓

Loading...