简体   繁体   English

SQL查询将整数转换为日期并查找月数差异

[英]SQL query to convert integer into date and find difference in number of months

I have 2 numbers(Integers) - 20210501 & 20210101 where the first 4 digits represent Year, next 2 digits represent Months and the last 2 digits represent Day.我有 2 个数字(整数)- 20210501 和 20210101,其中前 4 位数字代表年,接下来的 2 位数字代表月,最后 2 位数字代表日。 I want to write a SQL query to convert these integers to date and then find the difference in months between the 2 dates我想编写一个 SQL 查询来将这些整数转换为日期,然后找到两个日期之间的月差

At first convert varchar to date format and get month diff首先将 varchar 转换为日期格式并获取月份差异

-- SQL SERVER -- SQL 服务器

SELECT DATEDIFF(MONTH, CONVERT(varchar, CAST('20210101' AS DATE), 23), CONVERT(varchar, CAST('20210501' AS DATE), 23)) month_diff

Alternate way替代方式

-- SQL SERVER -- SQL 服务器

SELECT DATEDIFF(MONTH, CAST(CONVERT(varchar, CAST('20210101' AS DATE), 23) AS date), CAST(CONVERT(varchar, CAST('20210501' AS DATE), 23) AS date)) month_diff

Your two integers are conveniently in the right format for dates.您的两个整数很方便地采用正确的日期格式。 So, you can convert to a string, then to a date and use datediff() :因此,您可以转换为字符串,然后转换为日期并使用datediff()

select datediff(month,
                convert(date, convert(varchar(255), @val1)),
                convert(date, convert(varchar(255), @val2))
               )

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

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