返回int的月数和年数?

时间:2015-03-20 21:49:40

标签: sql-server

这看起来很简单,但我似乎无法弄清楚。

如果我有几个月,例如61 那是5年零1个月。 如何编写一个选项以给我0105的价值?

3 个答案:

答案 0 :(得分:3)

据推测,你会得到这样的查询:

SELECT MONTHS
FROM MY_TABLE;

你可以做一些分工并获得年数:

SELECT MONTHS / 12 AS YEARS
FROM   MY_TABLE;

接下来,您需要获得剩余的月数。 Modulo数学运算用于此:

SELECT MONTHS % 12 AS MONTHS,
       MONTHS / 12 AS YEARS
FROM   MY_TABLE;

现在您需要format it

SELECT FORMAT(MONTHS % 12 AS MONTHS, '00'),
       FORMAT(MONTHS / 12 AS YEARS, '00')
FROM   MY_TABLE;

最后,将两个结果汇总在一起:

SELECT CONCAT(FORMAT(MONTHS % 12 AS MONTHS, '00'),
              FORMAT(MONTHS / 12 AS YEARS, '00')) AS RESULT
FROM   MY_TABLE;

答案 1 :(得分:1)

您需要一些casecast/12%12

declare @value int
set @value=61
select 
case when len(cast(@value%12 as int))=1 then '0'+cast(@value%12 as varchar(1)) else cast(cast(@value%12 as int)as varchar(2)) end+
case when len(cast(@value/12 as int))=1 then '0'+cast(@value/12 as varchar(1)) else cast(cast(@value/12 as int)as varchar(2)) end 

输出 0105

答案 2 :(得分:1)

这里有两种可能的解决方案:

DECLARE @n INT = 61

SELECT RIGHT(REPLACE(CONVERT(varchar(8),DATEADD(Month,@n,'2000-01-01'),1),'/',''),4)

SELECT RIGHT(CAST(10000+@n%12*100+@n/12 AS VARCHAR(5)),4)