mysql - 在 MySQL 中转换为十进制

标签 mysql casting decimal

我正在尝试像这样在 MySQL 中转换为 Decimal:

CAST((COUNT(*) * 1.5) AS DECIMAL(2))

我正在尝试将表中的行数(乘以 1.5)转换为点后两位数的 float 。

SQL 代码:

 SELECT CONCAT(Guardian.title, ' ', 
               Guardian.forename, ' ', 
               Guardian.surname) AS 'Guardian Name', 
               COUNT(*) AS 'Number of Activities', 
               (COUNT(*) * 1.5) AS 'Cost'
 FROM Schedule
 INNER JOIN Child ON Schedule.child_id = Child.id
 INNER JOIN Guardian ON Child.guardian = Guardian.id
 GROUP BY Guardian
 ORDER BY Guardian.surname, Guardian.forename ASC

它会产生错误:

#1064 - You have an error in your SQL syntax; check the manual that 
corresponds to your MySQL server version for the right syntax to use 
near 'CAST((COUNT(*) * 1.5) AS DECIMAL(12,2))' at line 1.

再试一次,这个 Actor 也不行:

 SELECT CONCAT(Guardian.title, ' ', 
               Guardian.forename, ' ', 
               Guardian.surname) AS 'Guardian Name', 
               COUNT(*) AS 'Number of Activities', 
               CAST((COUNT(*) * 1.5) AS DECIMAL(8,2)) AS 'Cost'
 FROM Schedule
 INNER JOIN Child ON Schedule.child_id = Child.id
 INNER JOIN Guardian ON Child.guardian = Guardian.id
 GROUP BY Guardian
 ORDER BY Guardian.surname, Guardian.forename ASC

如何使用mysql将整数转换为十进制?

最佳答案

来自 MySQL 文档:Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC :

In standard SQL, the syntax DECIMAL(M) is equivalent to DECIMAL(M,0)

因此,您正在转换为具有 2 个整数位和 0 个小数位的数字。试试这个:

CAST((COUNT(*) * 1.5) AS DECIMAL(12,2)) 

关于mysql - 在 MySQL 中转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11830509/

相关文章:

mysql - 在MySQL中,如果索引复合选择中的列在排序中没有完全引用,排序是否会是最佳的?

MySQL 查询 ORDER BY DateTime 问题

c# - 将一种类型转换为另一种类型

mysql - SQL 查询比较十进制值不匹配并返回 NULL 值

PHP - 查找十进制数中零的个数

php - 旧版本的 PHP/MYSQL 是否有 NOT NULL 列的默认值?

mysql - 我可以使用 MySQL Join 进行 COUNT 操作吗?

java - (Java downcasting) 这个例子我做错了什么?

c++ - 将字符串文字分配给 char* : const_cast<char *> vs using char array

python - decimal.InvalidOperation 在 Series 中四舍五入值时出错