CAST to DECIMAL in MySQL(在 MySQL 中 CAST 到 DECIMAL)
问题描述
我正在尝试像这样在 MySQL 中转换为 Decimal:
I am trying to cast to Decimal in MySQL like this:
CAST((COUNT(*) * 1.5) AS DECIMAL(2))
我正在尝试将表中的行数(乘以 1.5)转换为在该点后有两位数的浮点数.
I'm trying to convert the number of rows in a table (times 1.5) to a floating point number with two digits after the point.
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.
再试一次,这个演员也不起作用:
Another try, this cast also doesn't work:
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将整数转换为小数?
How do I use mysql to cast from integer to decimal?
推荐答案
来自 MySQL 文档:定点类型(精确值)- DECIMAL、NUMERIC:
From MySQL docs: Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC:
在标准 SQL 中,语法 DECIMAL(M)
等价于 DECIMAL(M,0)
In standard SQL, the syntax
DECIMAL(M)
is equivalent toDECIMAL(M,0)
因此,您要转换为具有 2 个整数位和 0 个小数位的数字.试试这个:
So, you are converting to a number with 2 integer digits and 0 decimal digits. Try this instead:
CAST((COUNT(*) * 1.5) AS DECIMAL(12,2))
这篇关于在 MySQL 中 CAST 到 DECIMAL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 MySQL 中 CAST 到 DECIMAL
基础教程推荐
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01