根据 SQL 服务器中的月份计算年份

Calculate years based on months in 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

我可以使用 case 语句对所有这些进行硬编码,但我想知道是否有一种动态的方式来做到这一点。谢谢!

试试这个:

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 

请试试这个...

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

以下代码段显示了针对 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