首页 > 解决方案 > SQL : 当 period 格式为 yyyymm 时,从 SQL 服务器中提取最近 12 个月的数据

问题描述

我有一个看起来像这样的 SQL 服务器表

一个标题 另一个标题
202010 一个
202011
202012 C
202101 D
202102
202103 F
202104 G
202105 H
202106
202107 Ĵ
202108 ķ
202109 大号
202110
202111 ñ

monthid 是格式为 yyyymm 且具有整数数据类型的列。

我需要提取过去 12 个月的数据。

有人可以建议我怎么做吗

标签: sql-servertsqltime

解决方案


将您的数据转换为Pandas DataFrame. 您可以在此处查看如何操作。

# Convert date column to datetime
df['A header'] = pd.to_datetime(df['A header'], format='%Y%m')

# Sort and select last 12 months
df.sort_values(by='A header',ascending=True).set_index("A header").last("12M").reset_index()
| A header            | Another header   |
|:--------------------|:-----------------|
| 2020-12-01 00:00:00 | C                |
| 2021-01-01 00:00:00 | D                |
| 2021-02-01 00:00:00 | E                |
| 2021-03-01 00:00:00 | F                |
| 2021-04-01 00:00:00 | G                |
| 2021-05-01 00:00:00 | H                |
| 2021-06-01 00:00:00 | I                |
| 2021-07-01 00:00:00 | J                |
| 2021-08-01 00:00:00 | K                |
| 2021-09-01 00:00:00 | L                |
| 2021-10-01 00:00:00 | M                |
| 2021-11-01 00:00:00 | N                |

推荐阅读