SQL : 当周期为 yyyymm 格式时,从 SQL 服务器中提取最近 12 个月的数据

SQL : Extract last 12 months of data from SQL server when period is in the format of yyyymm

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

A header Another header
202010 A
202011 B
202012 C
202101 D
202102 E
202103 F
202104 G
202105 H
202106 I
202107 J
202108 K
202109 L
202110 M
202111 N

monthid 是 yyyymm 格式的列,数据类型为整数。

我需要提取最近 12 个月的数据。

有人可以建议我怎么做吗

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

# 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                |

您可以使用以下查询:

SELECT *
FROM YourTable
WHERE [A header] >= YEAR(DATEADD(month, -12, GETDATE())) * 100 + MONTH(DATEADD(month, -12, GETDATE()))

db<>fiddle

由于您将日期存储为整数,因此情况变得更糟。相反,您应该将月份的最后一天 存储为 date 类型 ,然后您可以

WHERE [A header] >= DATEADD(month, -12, GETDATE()))

您可以将该列转换为 datetime,然后只需在查询中使用它,如下所示:

SELECT *
FROM (
SELECT *, CONVERT(DATETIME, CONVERT(VARCHAR, A) + '01') MethodIdDateTime FROM Sample
 ) e
 WHERE 
   MethodIdDateTime >= DATEADD(MONTH, -12, GETDATE())

SQL Fiddle

select *
from [TableName]
where convert(date,left(A header,4)+'- 
'+right(A header,2)+'-01')>DATEADD(month, -12, GETDATE())
Order by convert(date,left(A header,4)+'-'+right(A header,2)+'-01') desc

我只修改了@Charlieface 查询,

CREATE TABLE #YourTable (
  "A header" INTEGER,
  "Another header" VARCHAR(1)
);

INSERT INTO #YourTable
  ("A header", "Another header")
VALUES
  ('202010', 'A'),
  ('202011', 'B'),
  ('202012', 'C'),
  ('202101', 'D'),
  ('202102', 'E'),
  ('202103', 'F'),
  ('202104', 'G'),
  ('202105', 'H'),
  ('202106', 'I'),
  ('202107', 'J'),
  ('202108', 'K'),
  ('202109', 'L'),
  ('202110', 'M'),
  ('202111', 'N');

  declare  @To int =202012
  declare @From int = format(dateadd(month,-12, cast(concat(@To,'01') as date)),'yyyyMM')
  --select @From
  SELECT *
FROM #YourTable
WHERE ([A header] >= @From and [A header]<=@To)
drop table #YourTable