sql - Postgress to_date 和提取组合
问题描述
我在 postgres 中有下表:
+----------+-------+
| date | money |
+----------+-------+
| 20191212 | 10 |
+----------+-------+
| 20200101 | 20 |
+----------+-------+
| 20200102 | 30 |
+----------+-------+
我想创建 2 个查询,按年按金额分组,按月分组。日期列是 varchar,我无法将其转换为日期。
+------+-------+
| year | money |
+------+-------+
| 2019 | 10 |
+------+-------+
| 2020 | 50 |
+------+-------+
+---------+-------+
| month | money |
+---------+-------+
| 2019-12 | 10 |
+---------+-------+
| 2020-01 | 50 |
+---------+-------+
我试图结合 to_date 和 extract 函数,但它不起作用:
WITH date_year AS (
SELECT to_date(date, 'YYYYMMDD') as date_year from sales
)
SELECT EXTRACT(YEAR FROM date_year) as year, sum(money) as sum FROM sales group by year
WITH date_month AS (
SELECT to_date(date, 'YYYYMMDD') as date_month from sales
)
SELECT EXTRACT(MONTH FROM date_month) as month, sum(money) as sum FROM sales group by month
解决方案
group by
您可以在子句中使用函数或别名:
select extract(year from to_date(date, 'YYYYMMDD')) as y_year, sum(money) as sum
from sales
group by y_year
select extract(year from to_date(date, 'YYYYMMDD')) || '-' || extract(month from to_date(date, 'YYYYMMDD')) as year_month, sum(money) as sum
from sales
group by year_month
我使用了y_year
因为year
在 postgres 中保留。
您也可以考虑使用date_trunc
:
select date_trunc('month', to_date(date, 'YYYYMMDD')) as year_month, sum(money) as sum
from sales
group by year_month
推荐阅读
- c - 静态结构初始化
- python - 如何使用 DataFrame 中的每一行来过滤查询
- ansible - 角色复制和执行,为可以有多个条目的参数传递多个变量结构
- python - 获取 MongoDB 中集合的每个值的特定范围
- laravel - Auth::user() 在新路由中为空
- javascript - Bootstrap Carousel 更改特定颜色的 div
- c# - 播放器不工作的统一跳转代码
- python - Pandas 通过迭代现有的 df 行创建单独的 df
- javascript - 为什么在这种情况下超过了最大调用堆栈?
- python - 如何在具有输入名称的函数中定义列表?