[英]Convert number of years into dateName?
So I'm calculating the datediff in years and getting a numerical value (Ex: 16.166666) What would be the best solution to turn that value into Date Names. 因此,我计算年份中的约会数并得到一个数值(例如:16.166666)将该值转换为日期名称的最佳解决方案是什么。
For example 16.166 years would turn into: 16 years and 1 month? 例如16。1666年会变成:16年1个月?
Example 例
Declare @Value float= 16.166
Select Years = floor(@Value)
,Months = floor((@Value - floor(@Value)) * 12)
,OrAsStr = ltrim(
replace(
replace(
concat(' ',floor(@Value),' Years ',floor((@Value - floor(@Value)) * 12),' Months')
,' 1 Years ',' 1 Year ')
,' 1 Months',' 1 Month')
)
Returns 返回
Years Months OrAsStr
16 1 16 Years 1 Month
According to your comment 根据你的评论
I have two date columns which I need to find the date difference , then convert to a string: Ex: 16 years and 1 month. 我有两个日期列,我需要找到日期差异,然后转换为字符串:例如:16年零1个月。
You can do like 你可以这样做
DECLARE
@Start DATE = '2000-01-01',
@End DATE = '2016-02-01';
SELECT CAST(T.Years AS VARCHAR(10)) + ' Years and ' +
CAST(DATEDIFF(Month, @Start, DATEADD(Year, - T.Years, @End)) AS VARCHAR(2)) + ' Months.'
FROM
(
SELECT DATEDIFF(Year, @Start, @End) Years
) T;
OR 要么
SELECT CAST(DATEDIFF(Year, @Start, @End) AS VARCHAR(10)) +
' Years and ' +
CAST(
DATEDIFF(
Month,
@Start,
DATEADD(Year, - DATEDIFF(Year, @Start, @End),
@End
)
) AS VARCHAR(2)) + ' Months.';
Returns 返回
+------------------------+
| 16 Years and 1 Months. |
+------------------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.