转换数字

时间:2019-05-23 00:11:11

标签: tsql

我有一个计算并使它工作(第2节),然后我们也需要更改计算:(((bkesty * 12)-bkdptime)/ 12并且不确定如何适应它以将结果5.6666更改为5y8m

第1节新计算

bkesty值= 14.75 bkdptime = 109

var record = User.find(1).exec(function(err, u){
    return u[0];
});

var record = User.find(1).exec(function(err, u){
    return u;
});

结果是5.6666

然后我需要显示5y8m的结果

它适用于下面的旧计算,我不确定如何更改公式以使用第1节中的上述计算获得结果

第2节旧计算

var record = User.find(1).exec(function(err, u){
    console.log(Object.keys(u[0]));
});

任何帮助都会很棒

2 个答案:

答案 0 :(得分:0)

这应该使您入门。您可能要使用Round()来调整月份数。

-- Sample data.
declare @AMASST as Table ( ASTNO VarChar(10), bkesty Float, bkdptime Float );
insert into @AMASST ( ASTNO, bkesty, bkdptime ) values
  ( 'DR-080426', 5.6666, 0.0000 );

-- The following assumes that the estimated life is never negative.
select ASTNO, bkesty, bkdptime, EstLife,
  -- Just take the integer part for the years.
  Floor( EstLife ) as IntegerYears,
  -- Subtract the integer part from the floating value to get the fractional part.
  -- Multiply by 12 to get the number of months, take the integer part.
  ( EstLife - Floor( EstLife ) ) * 12 as FloatingMonths,
  -- Put it all together with casts to strings.
  Cast( Floor( EstLife ) as VarChar(4) ) + 'y' +
    Cast( Floor( ( EstLife - Floor( EstLife ) ) * 12 ) as VarChar(2) ) + 'm' as "ESTIMATED_LIFE"
  from @AMASST cross apply
    -- Perform the New Calculation and make it available as   EstLife .
    ( select ( ( bkesty * 12 ) - bkdptime ) / 12 as EstLife ) Placeholder
  where ASTNO = 'DR-080426';

答案 1 :(得分:0)

首先,最后不要除以12。您已经有整数个月。除以12可得出年数,但会四舍五入。

一旦您有了总的月份数,请除以12以获得年份数, 剩下的就是几个月了。

create function dbo.MonthsToStr ( @Months int ) 
returns varchar(20) as
begin
  declare @Result varchar(20)
  -- Do we need to deal with negative values?

  if @Months < 0 
    set @Result =  '-' + dbo.MonthsToStr(-@Months)
  else
    -- Divide by 12 to get the number of years
    -- The remainder is the number of months
    set @Result =  CAST(@Months/12 as varchar(10) ) + 'y'
                 + CAST(@months%12 as varchar(2) ) + 'm'

  return @Result
end
go

select dbo.MonthsToStr(68)