将数字格式的分钟转换为小时和分钟格式

时间:2016-05-06 14:01:01

标签: sql sql-server-2008

我在名为'Efforts_in_minutes'的列中有1064分钟,我需要输出格式为HH:MM(即17:44)。我试过了下面的查询

SELECT Cast(Round(Total_Effort_in_Minutes / 60, 0, 2) AS VARCHAR) 
        + ':' 
        + Cast(Total_Effort_in_Minutes % 60 AS VARCHAR(2))
FROM   PPS 

我的输出为17.000000:44但我需要的是17:44

请告知如何实现这一目标。

4 个答案:

答案 0 :(得分:3)

不需要使用Round功能。只做整数除法:

select CAST(CAST(Total_Effort_in_Minutes AS INT) / 60 AS VARCHAR)
    + ':' + CAST(Total_Effort_in_Minutes  % 60 AS VARCHAR(2) )

如果您的列 Total_Effort_in_Minutes 已经有整数数据类型,那么您可以简化为:

select CAST(Total_Effort_in_Minutes / 60 AS VARCHAR)
    + ':' + CAST(Total_Effort_in_Minutes  % 60 AS VARCHAR(2) )

如果你需要用零填充分钟部分来获得至少2位数,那么:

select RIGHT('0' + CAST(CAST(Total_Effort_in_Minutes AS INT) / 60 AS VARCHAR), 2)
    + ':' + CAST(Total_Effort_in_Minutes  % 60 AS VARCHAR(2) )

答案 1 :(得分:1)

SELECT DATEADD(MI,Total_Effort_in_Minutes,TIMEFROMPARTS(0,0,0,0,0))
FROM   PPS

最佳实践:客户应根据区域设置决定如何表示时间,以允许24H时钟与AM / PM等变体。

答案 2 :(得分:0)

请参阅此链接:https://stackoverflow.com/a/19887500/6298495

创建内联函数是链接中提供的一个很好的解决方案。

答案 3 :(得分:0)

只是为了好玩:

apiRouter.post('/', function(req, res) {
    console.log(req.body);
    var schedule = new Schedules();

    schedule.firstName = req.body.firstName;
    schedule.real_name = req.body.real_name;
    schedule.userName = req.body.userName;
    schedule.email = req.body.email;
    schedule.userId = req.body.userId;
    schedule.date = req.body.date;
    schedule.channel = req.body.channel;
    schedule.expecting = req.body.expecting;

    schedule.save(function(err, schedule) {
        if (err) res.send(err);
        res.json({message: 'Schedule was created'});
    });
});