0

谁能告诉我如何以人类可读的形式(例如 1d 5h 2m 13s)格式化给定的秒数(例如 16742 秒)

  • 使用 BO 字段公式
  • 从 T-SQL SELECT 语句中(其中 Duration as Seconds 来自 SUM 聚合)?
4

2 回答 2

1

我个人会为此制作一个 TSQL 函数。以下是您可以调整的示例:

IF(OBJECT_ID('FN_STRING_TO_TIME', 'FN') IS NOT NULL)
    DROP FUNCTION FN_STRING_TO_TIME
GO

CREATE FUNCTION dbo.FN_STRING_TO_TIME( 

    -- Seconds to convert
    @pSeconds   INT
)
RETURNS VARCHAR(12)
---------------------------------------------------------------------------------------
-- Developer:       Linus Brimstedt
-- Date:        2009-03-17
--
-- Function:        Returns the given seconds in H:MM:SS format
--          
-- Output:          String in format H:MM:SS
--          
---------------------------------------------------------------------------------------
BEGIN

-----------------------------
-- Variables
-----------------------------

    DECLARE @output     VARCHAR(30) -- Describe the variables

    DECLARE @minutes    INT
    DECLARE @hours      INT

-----------------------------
-- Implementation
-----------------------------

    SET @minutes = @pSeconds / 60
    SET @pSeconds = @pSeconds % 60

    SET @hours = @minutes / 60
    SET @minutes = @minutes % 60

-----------------------------
-- Return output
-----------------------------
    RETURN  CAST(@hours AS VARCHAR) + ':'
    +   dbo.FN_STRING_LPAD(@minutes, 2, '0') + ':'
    +   dbo.FN_STRING_LPAD(@pSeconds, 2, '0') 
END
GO

-- Test
DECLARE @seconds    INT
,   @got        VARCHAR(12)
,   @expected   VARCHAR(12)

SELECT  @seconds = 67
,   @expected = '0:01:07'
SET @got = dbo.FN_STRING_TO_TIME(@seconds)

IF(@got != @expected)
    RAISERROR('FN_STRING_TO_TIME(%d) returned bad value: Expected: %s, got %s', 11, 11, @seconds, @expected, @got)

SELECT  @seconds = 60 * 60 * 7 + 60 * 14 + 34
,   @expected = '7:14:34'
SET @got = dbo.FN_STRING_TO_TIME(@seconds)

IF(@got != @expected)
    RAISERROR('FN_STRING_TO_TIME(%d) returned bad value: Expected: %s, got %s', 11, 11, @seconds, @expected, @got)

干杯/L

于 2009-03-17T22:23:43.727 回答
1

我已经使用 Deski 和四个变量完成了它。从小时测量开始,创建一些变量,在下面我的年变量是 vYears,我的月变量是 vMonths,我的天变量是 vDays,我的小时变量是 vHours。

vYears 使用以下计算:

=Floor(Sum(<Hours Billed by Date Billed>/24)/365.25)

vWeeks 使用以下计算:

=Floor(Sum((Sum(<Hours Billed by Date Billed>/24)/365.25)-<vYears>)*365.25/7)

vDays 使用以下计算:

=Floor(Sum(Sum((Sum(<Hours Billed by Date Billed>/24)/365.25)-<vYears>)*365.25/7-<vWeeks>)*52/24)

vHours 使用以下计算:

=Truncate(Sum((Sum(Sum((Sum(<Hours Billed by Date Billed>/24)/365)-<vYears>)*365/7-<vWeeks>)*52/24-<vDays>)*24) , 2)

然后我可以通过执行以下操作来输出这些变量:

=<vYears>+" Years "+<vWeeks>+" Weeks "+<vDays>+" Days "+<vHours>+" Hours"

如果您需要更多信息,请不要犹豫。

谢谢,

马特

于 2009-07-08T03:04:19.627 回答