从TIME_FORMAT()中删除00值

时间:2017-12-31 21:12:50

标签: mysql sql

来自此查询

SELECT TIME_FORMAT("19:00:00", "%H Hours, %i Minutes, %s Seconds");

我得到了结果19 Hours, 00 Minutes, 00 Seconds

我想得到的是19 Hours仅在Minutes and Seconds = 00

如果我有19:00:55,我希望得到19 Hours, 55 Seconds

如果我有19:55:00,我希望得到19 Hours, 55 Minutes

使用SQL

删除00

3 个答案:

答案 0 :(得分:4)

我测试了这个:

pod

输出:

SET @t = '19:00:00';

SELECT CONCAT_WS(', ', 
  CONCAT(NULLIF(TIME_FORMAT(@t, '%H'), '00'), ' hours'), 
  CONCAT(NULLIF(TIME_FORMAT(@t, '%i'), '00'), ' minutes'), 
  CONCAT(NULLIF(TIME_FORMAT(@t, '%s'), '00'), ' seconds')) AS time_expr;

当我把时间设定为别的时候:

+-----------+
| time_expr |
+-----------+
| 19 hours  |
+-----------+

输出:

SET @t = '19:00:05';

它甚至可以处理零小时:

+----------------------+
| time_expr            |
+----------------------+
| 19 hours, 05 seconds |
+----------------------+

输出:

SET @t = '00:43:00';

答案 1 :(得分:4)

这是比尔答案的一个细微变化,它在时间部分处理复数:

SELECT CONCAT_WS(', ', 
                 CONCAT(hour(t), ' hour', (case hour(t) when 0 then NULL when 1 then '' else 's' end)), 
                 CONCAT(minute(t), ' minute', (case minute(t) when 0 then NULL when 1 then '' else 's' end)), 
                 CONCAT(second(t), ' second', (case second(t) when 0 then NULL when 1 then '' else 's' end))
                ) AS time_expr
from (SELECT CAST('19:01:01' as time) as t) x

答案 2 :(得分:2)

你可以试试这个。

SELECT TIME_FORMAT( "19:00:00", 
    CONCAT(IF(HOUR("19:00:00") <> 0, "%H Hours", "") ,
    IF(MINUTE("19:00:00") <> 0, ", %i Minutes", "") ,
    IF(SECOND("19:00:00") <> 0, ", %s Seconds", ""))
);