[英]MariaDB Trigger Calculating Time Difference as a decimal of total hours and tenth of hour always rounding up
I have a table that contains these columns:我有一个包含这些列的表:
start_time datetime
end_time datetime
billable_time decimal(3,1)
The billable_time
column is calculated with a trigger on insert and update as the total number of hours and tenth of hour as a decimal; billable_time
列通过插入和更新触发器计算为总小时数,十分之一小时为小数; however, I want it to always round up the decimal as opposed to rounding to the nearest digit.但是,我希望它总是四舍五入而不是四舍五入到最接近的数字。 When creating the trigger, I cannot figure out how to make it always round up the decimal.创建触发器时,我不知道如何让它总是四舍五入。 This trigger calculates it correctly, but it rounds it down if that is the nearest digit:此触发器正确计算它,但如果这是最接近的数字,它会将其向下舍入:
SET new.billable_time = CAST(TIME_TO_SEC(TIMEDIFF(new.end_time, new.start_time))/3600 as decimal(3,1))
For example:例如:
start time = 2020-06-01 11:00:00
end_time = 2020-06-01 12:22:08
Results in结果是
billable_time = 1.4
But it should be 1.5 if it always rounds up.但如果它总是向上取整,它应该是 1.5。
I have tried using the CEIL()
and CEILING()
functions, but they round it up to the nearest integer, which is 2.我曾尝试使用CEIL()
和CEILING()
函数,但它们将其四舍五入到最接近的 integer,即 2。
I cannot seem to figure out how to make it do what I want.我似乎无法弄清楚如何让它做我想做的事。 Is it possible to do this in a trigger?是否可以在触发器中执行此操作? Any help would be greatly appreciated.任何帮助将不胜感激。 The database is MariaDB v10.4.13.数据库为 MariaDB v10.4.13。
Thanks in advance.提前致谢。
A simple solution is to add half of a tenth of second to the value before cast
ing it:一个简单的解决方案是在强制转换之前cast
十分之一秒的一半添加到该值:
SET new.billable_time = CAST(
TIME_TO_SEC(TIMEDIFF(new.end_time, new.start_time))/3600 + 0.05
AS decimal(3,1)
)
You can also use ceil()
: the idea is to first divide by 360
instead of 3600
, then round with ceil()
, and finally divide by 10
:您也可以使用ceil()
:想法是先除以360
而不是3600
,然后用ceil()
舍入,最后除以10
:
SET new.billable_time =
CEIL(TIME_TO_SEC(TIMEDIFF(new.end_time, new.start_time))/360) / 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.