开发者

MySQL: Digits (1.75) to Friendly Time (1 hour and 45 minutes)

In my MySQL database, I have a float field named "HoursSpent" with values like "0.25", "1.75", "2.5", etc. Is there a way that I can have my SELECT statement format those values in a friendly format like this?:

0.25 = 15 minutes

1.75 = 1 hour and 45 minutes

2.5 = 2 hours and 30 minutes

The "HoursSpent" field is supposed to only have values in 0.25 increments, but if somebody were to put something random like 0.16, it would be nice if the SELECT statement handled that by rounding it up to the nearest 0.25 (so in this case 0.16 would become开发者_JAVA百科 0.25, or 15 minutes).


SELECT CONCAT(CASE WHEN FLOOR(HoursSpent)>0 THEN CONCAT(FLOOR(HoursSpent),' Hours and ') ELSE '' END,60*(HoursSpent-FLOOR(HoursSpent)),' Minutes') As Formatted
FROM   table;

results in:

+--------------------+
| Formatted          |
+--------------------+
| 2 Hours 45 Minutes |
| 3 Hours 30 Minutes |
| 4 Hours 15 Minutes |
| 15 Minutes         |
+--------------------+

*EDITv2

Made it use singular and plural form:

SELECT  CONCAT(
          CASE
            WHEN FLOOR(HoursSpent)>0 THEN
              CONCAT(FLOOR(HoursSpent),
                CASE
                  WHEN FLOOR(HoursSpent)=1 THEN
                    ' Hour and '
                  ELSE
                    ' Hours and '
                END
              )
            ELSE
              ''
          END,
          60*(HoursSpent-FLOOR(HoursSpent)),
          ' Minutes'
        ) As Formatted
FROM   table;

Resulting in:

+------------------------+
| Formatted              |
+------------------------+
| 2 Hours and 45 Minutes |
| 3 Hours and 30 Minutes |
| 4 Hours and 15 Minutes |
| 15 Minutes             |
| 1 Hour and 30 Minutes  |
+------------------------+

Sorry for delay. ;-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜