mysql - 在 mySQL 中将返回值格式化为小数点后两位

标签 mysql sql formatting

我有下面的查询,它从我的数据库中检索数据,并在其中汇总所有值并将其除以 60 以将其转换为小时:

SELECT date(att.`date`) as dtDate, 
(select sum(early_leave) from `attendance` where `attendance`.early_leave
> 0 and date(`attendance`.`date`) = date(att.date)) / 60 as EL

FROM `attendance` as att 

where date(att.`date`) BETWEEN '2018-08-9' and '2018-08-23'
group by date(att.`date`)
order by date(att.`date`)

它的输出是这样的:

output 1

现在,我希望它的格式为小数点后两位,所以我这样做:

SELECT date(att.`date`) as dtDate, 
(select format(sum(early_leave),2) from `attendance` where `attendance`.early_leave
> 0 and date(`attendance`.`date`) = date(att.date)) / 60 as EL

FROM `attendance` as att 

where date(att.`date`) BETWEEN '2018-08-9' and '2018-08-23'
group by date(att.`date`)
order by date(att.`date`)

但是为什么有些输出是这样的:

output 2

我预计 2018-08-10 的第二个值是 28 等等。有人知道为什么会这样吗?或者我是否以正确的方式格式化它?

最佳答案

您需要将 format 作为最后一件事,因为除以 60 会导致结果中出现额外的小数位:

format((select sum(early_leave) from `attendance` where `attendance`.early_leave
> 0 and date(`attendance`.`date`) = date(att.date)) / 60, 2) as EL

如果不想显示不需要的小数位,只需添加0即可!

format((select sum(early_leave) from `attendance` where `attendance`.early_leave
> 0 and date(`attendance`.`date`) = date(att.date)) / 60, 2)+0 as EL

例如:

select format(2.00,2)+0, format(1.5,2)+0, format(1.55,2)+0

输出:

2, 1.5, 1.55

关于mysql - 在 mySQL 中将返回值格式化为小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52417046/

相关文章:

python - 修复 Python 中的错误?

mysql - 复杂的MySQL查询问题

sql - 如何通过 HireDate 和 TerminationDate 在公司中获得最多的员工?

mysql - Electron + MySQL 抛出安全警告

c++ - Firebird /IBPP : How to retrieve ID generated by a database autoincrement?

SQL Delete with Join 和 Foreign Key 约束

c++ - 是否可以自定义 XCode 的缩进样式?

Vim:重新格式化和重新缩进注释的自动方式?

PHP PDO MYSQL 复合选择语句

javascript - TypeORM 中的 ColumnTypeUndefinedError