SQL Server中按月计算年



我想编写一个函数,以月数作为参数,并执行以下操作:

IF @months = 3 THEN '3 Months'
IF @months = 6 THEN '6 Months'
IF @months = 12 THEN '1 Year'
IF @months = 18 THEN '1.5 Year'
IF @months = 24 THEN '2 Year'
.... and so on

我可以硬编码所有这些用例语句,但我想知道是否有一种动态的方式来实现它。谢谢!

试试这个:

DECLARE @month INT=26
SELECT CASE WHEN @month >=12 
THEN CONCAT(CAST(@month/12.0 AS DECIMAL(5,1)),' Year') 
ELSE CONCAT(@month,' Months') END 

Please try this…

SELECT IIF(@month<12,CONCAT(@Month,' Months'),CONCAT(CONVERT(DECIMAL(9,1),@Month/12.0),' Year'));

下面的代码片段显示了month值在1到36之间的计算和结果

declare @month INT = 0
while @month < 36 begin
set @month = @month + 1
-- This is the actual "function"
select case when @month < 12 then concat (@month, ' month(s)')
else concat (cast (@month/12.0 as decimal (6,2)), ' year(s)')
end
end

最新更新