简体   繁体   English

在SQL中将小时转换为分钟

[英]Converting hours into minutes in SQL

i'm trying to write a regular expression that will convert the hours into minutes. 我正在尝试编写一个将小时转换为分钟的正则表达式。 Currently I have a value which give me the number of hours before the dot and the number of minutes after the dot, for example 6.10 is 6 hours and 10 minute. 目前我有一个值,它给出了点之前的小时数和点之后的分钟数,例如6.10是6小时10分钟。

Can i use a regular expression to look for the value before the dot and multiply by 60 (to get minutes) and then add the value after the dot (which is already in minutes)? 我可以使用正则表达式来查找点之前的值并乘以60(得到分钟),然后在点之后添加值(已经是几分钟)?

So as per the example used before, it would do: (6 * 60) + 10 因此,根据之前使用的示例,它将执行:(6 * 60)+ 10

Thank you! 谢谢!

If your value "6.10" is stored as a string, convert it to a number first: 如果您的值“6.10”存储为字符串,请先将其转换为数字:

SET @Input = CAST(@InputString AS FLOAT)

Then, use Modulus and Floor . 然后,使用ModulusFloor

Total Minutes = The fractional part * 100 + the whole number part * 60. 总分钟数=小数部分* 100 +整数部分* 60。

So if your value 6.10 is contained in a variable named @Input, then you can get the value you wish with 因此,如果您的值6.10包含在名为@Input的变量中,那么您可以获得所需的值

SET @Output = (@Input % 1) * 100 + FLOOR(@Input, 0)  * 60

If it's in a table then something more like this would be appropriate: 如果它在一个表中,那么更合适的东西是合适的:

SELECT (Input % 1) * 100 + FLOOR(Input, 0) * 60 Output 
FROM   Table

The above only works if minutes are zero padded, eg 6 hours five minutes = 6.05. 以上仅在分钟为零填充时有效,例如6小时5分钟= 6.05。 If you instead represent minutes without padding (6 hours five minutes = 6.5) then use the method that under suggests. 如果你代表没有填充的分钟(6小时5分钟= 6.5),那么使用建议的方法。

There's a STRTOK function to tokenize a string and then it's just: 有一个STRTOK函数来标记字符串然后它只是:

select '12.34' as x, 
    cast(strtok(x,'.',1) as int) * 60 + cast(strtok(x,'.',2) as int)

Regular expressions is probably an overkill for such a simple string manipulation. 对于这种简单的字符串操作,正则表达式可能有点过分。 All you need is INDEX function to get the location of the dot and SUBSTR function to get hours and minutes. 您只需要INDEX函数来获取点和SUBSTR函数的位置以获得小时和分钟。

Dot position: 点位置:

 select INDEX([yourstring], '.') 

Hours (before the dot): 小时(点前):

 select SUBSTR([yourstring], 1, INDEX([yourstring], '.')  - 1)

Minutes (after the dot): 分钟(点后):

 select SUBSTR([yourstring], INDEX([yourstring], '.') + 1) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM