问题描述
我目前正在使用PostgreSQL在sql项目中工作,现在我的结果如下:
month | year | sales
----- + ---- + -----
7 | 2019 | 5300
8 | 2019 | 6600
9 | 2019 | 7100
7 | 2020 | 6900
8 | 2020 | 8800
9 | 2020 | 9500
使用以下代码:
select date_part('month',points_reward.created) as mes,date_part('year',points_reward.created) as ano,sum(available_points) as "sales"
from points_reward
group by 1,2
我正在尝试创建一个表格,向我显示这样的月份与年份:
| 2019 | 2020
--- + ---- + ----
7 | 5300 | 6900
8 | 6600 | 8800
9 | 7100 | 9500
在此先感谢您的提示或帮助,并抽出宝贵的时间阅读。
解决方法
通过将Filter
与SUM
函数一起使用将解决您的问题。
select
date_part('month',points_reward.created) as "Month",sum(available_points) filter (where date_part('year',points_reward.created)=2019) "2019",points_reward.created)=2020) "2020"
from points_reward
group by 1
您可以添加更多具有相同格式的年份的列
,尝试这样的事情:
select cte1.month,cte1.sales as '2019',cte2.sales as '2020' from
(select month,sum(available_points) as sales from points_reward where year=2019 group by month)
as cte1 inner join
(select month,sum(available_points) as sales from points_reward where year=2020 group by month)
as cte2 on cte1.month=cte2.month
order by cte1.month