PostgreSQL中的Year vs Month表

问题描述

我目前正在使用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

在此先感谢您的提示或帮助,并抽出宝贵的时间阅读。

解决方法

通过将FilterSUM函数一起使用将解决您的问题。

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

DEMO

您可以添加更多具有相同格式的年份的列

,

尝试这样的事情:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...