SQL时间转换

时间:2014-03-24 08:29:42

标签: sql sql-server sql-server-2008

我在转换时间方面遇到了麻烦。

我有一个名为'TotalTime'的表,它被设置为INT并且仅以秒为单位保存时间。我想将这些秒转换为天,小时,分钟,秒,例如01d 09:26:43。

现在我将向您展示我正在使用的代码:

SELECT [BuildID],[Product],[Program],


SUM(CASE WHEN [State] = 'Running' THEN cast(TotalTime as INT) ELSE 0 END) AS [Running],
SUM(CASE WHEN [State] = 'Break' THEN cast(TotalTime as INT) ELSE 0 END) AS [Break]


FROM [line_log].[dbo].[Line1Log]

GROUP BY [BuildID], [Product], [Program]

因此,您可以看到我正在对[State]列进行分组,并希望以上面提到的格式显示“TotalTime”的结果。

现在我已经尝试过这段代码,但它无法正常工作,因为我无法将INT转换为VARCHAR

SELECT [BuildID],[Product],[Program],

SUM(CASE WHEN [State] = 'Running' THEN CAST(FLOOR(TotalTime / 86400) AS VARCHAR(10))+'d ' + CONVERT(VARCHAR(5), DATEADD(SECOND, TotalTime, '19000101'), 8) ELSE 0 END) AS [Running]

FROM [line_log].[dbo].[Line1Log]

GROUP BY [BuildID], [Product], [Program]

以上内容不会以我想要的格式显示。

只是想知道是否有人愿意帮我这个?

感谢您花时间阅读本文:)

1 个答案:

答案 0 :(得分:1)

您应该在求和和分组后转换计算的秒数:

并使用VARCHAR(8)代替VARCHAR(5)

SELECT [BuildID],[Product],[Program],
    CAST(FLOOR([Running] / 86400) AS VARCHAR(10))+'d ' + CONVERT(VARCHAR(8), DATEADD(SECOND, [Running], '19000101'), 8) AS [Running],
    CAST(FLOOR([Break] / 86400) AS VARCHAR(10))+'d ' + CONVERT(VARCHAR(8), DATEADD(SECOND, [Break], '19000101'), 8) AS [Break]
FROM (
    SELECT [BuildID],[Product],[Program],
        SUM(CASE WHEN [State] = 'Running' THEN cast(TotalTime as INT) ELSE 0 END) AS [Running],
        SUM(CASE WHEN [State] = 'Break' THEN cast(TotalTime as INT) ELSE 0 END) AS [Break]
    FROM [line_log].[dbo].[Line1Log]
    GROUP BY [BuildID], [Product], [Program]
) T