简体   繁体   English

SQL 挖掘过去 n 年的数据时出现算术溢出错误

[英]SQL Arithmetic Overflow error while mining data for last n years

im new to SQL.我是 SQL 的新手。 I am trying to extract data from a table for the last 4 years but I am getting the below error我正在尝试从表中提取过去 4 年的数据,但出现以下错误

SELECT * FROM fact.ClaimDetail WHERE EobPrintDateCode > DATEADD(year,-4,GETDATE())

Msg 8115, Level 16, State 2, Line 30
Arithmetic overflow error converting expression to data type datetime.

The date format is as below YYYMMDD日期格式如下 YYYMMDD

df['EobPrintDateCode']
Out[89]: 
0    20060113
1    20060113
2    20060113
3    20060113
4    20060113

Do I need to convert this to another format before I do my select query?在执行 select 查询之前,是否需要将其转换为另一种格式? Please help请帮忙

If your datecode is an integer, you can convert it to a date in a two-step process:如果您的日期代码是 integer,您可以分两步将其转换为日期:

SELECT *
FROM fact.ClaimDetail
WHERE TRY_CONVERT(date, TRY_CONVERT(VARCHAR(255), EobPrintDateCode)) > DATEADD(year,-4, GETDATE())

You can also phrase this using operations only on GETDATE() .您也可以仅在GETDATE()上使用操作来表达这一点。 Once again, assuming an integer:再次假设 integer:

WHERE EobPrintDateCode >= (YEAR(GETDATE()) - 4) * 10000 + MONTH(GETDATE()) * 100 + DAY(GETDATE())

Because you are subtracting 4 years, the date arithmetic just works like this even for leap years.因为您要减去 4 年,所以即使对于闰年,日期算术也是如此。

you can use cast to convert value to date您可以使用 cast 将值转换为日期

SELECT *
FROM fact.ClaimDetail
WHERE cast(cast(EobPrintDateCode AS varchar(8)) AS date) > DATEADD(year,-4, GETDATE())
SELECT * 
FROM fact.ClaimDetail 
WHERE year(EobPrintDateCode) > year(getdate())-4;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM