我在Postgres服务器上有以下数据库表:
id date Product Sales
1245 01/04/2013 Toys 1000
1245 01/04/2013 Toys 2000
1231 01/02/2013 Bicycle 50000
456461 01/01/2014 Bananas 4546
我想创建一个查询,给出Sales列的SUM,并按月和年将结果分组如下:
Apr 2013 3000 Toys
Feb 2013 50000 Bicycle
Jan 2014 4546 Bananas
有什么简单的方法吗?
为什么不直接使用date_part函数呢?https://www.postgresql.org/docs/8.0/functions-datetime.html
SELECT date_part('year', txn_date) AS txn_year,
date_part('month', txn_date) AS txn_month,
sum(amount) as monthly_sum
FROM payment
GROUP BY txn_year, txn_month
order by txn_year;
我还需要找到按年和月分组的结果。
当我按时间戳对它们进行分组时,求和函数用日期和分钟对它们进行分组,但这不是我想要的。
使用这个查询可能对您有帮助。
select sum(sum),
concat(year, '-', month, '-', '01')::timestamp
from (select sum(t.final_price) as sum,
extract(year from t.created_at) as year,
extract(month from t.created_at) as month
from transactions t
where status = 'SUCCESS'
group by t.created_at) t
group by year, month;
交易表
查询结果
如图所示,在“2022-07-01”中,我在表中有两列,在查询结果中它们被分组在一起。